<template>
  <div class="trade-container" v-loading.fullscreen.lock="globalLoading" element-loading-text="加载中..."
    element-loading-background="rgba(255, 255, 255, 0.9)">
    <div>
      <!-- 交易行说明区域 - 现在放在搜索栏之前 -->
      <div class="market-notice">
        <div class="notice-header">
          <h3>交易行说明</h3>
          <el-button type="text" @click="noticeVisible = !noticeVisible">
            {{ noticeVisible ? '收起' : '展开' }}
            <el-icon>
              <ArrowDown v-if="!noticeVisible" />
              <ArrowUp v-else />
            </el-icon>
          </el-button>
        </div>

        <div v-show="noticeVisible" class="notice-content">
          <p>由于游戏内部交易市场可交易物品有限且需要在线售卖，所以制作了一个离线交易市场。</p>
          <p>为保证数据同步，集市内进行买卖操作时，需要将<strong>游戏账号下线</strong>。</p>
          <p>集市内的交易使用的货币是{{ CURRENCY.XIN_BEAN }}，交易成功后系统将向<strong>卖家</strong>收取<strong>5%的手续费（限时下调）</strong>(最低1{{ CURRENCY.XIN_BEAN }})。</p>

          <div class="notice-warning">
            <h4>关于详细的交易细则</h4>
            <el-link style="font-size: 16px;" href="https://seerxin.com/url/trade">点击查看细则</el-link>
            <p><strong>XIN服管理组不会对交易产生的纠纷进行处理</strong></p>
          </div>
        </div>
      </div>

      <!-- 新增：移动端独立余额模块（仅在移动端显示） -->
      <div class="mobile-balance-section mobile-only">
        <el-card class="mobile-account-info" shadow="never">
          <el-row :gutter="10" style="font-size: 14px;">
            <!-- <el-col :span="12"> -->
              <!-- <div class="mobile-balance">
                <svg t="1744176905853" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6957" width="20" height="20"><path d="M60.974268 623.892437A430.636588 430.636588 0 0 1 13.963573 508.087872c-7.074877-29.788956-15.35993-67.956055-13.684302-110.219135 2.513443-62.277535 8.005782-112.360217 40.401271-189.252958 79.685456-188.973686 246.689788-247.527602 395.634566-183.9468 148.758597 63.673892 87.132695 227.606238 279.271458 376.644106 53.061577 41.145995 52.130672 45.335067 89.087595 64.790978 36.863832 19.455912 73.541484 36.026018 101.282448 53.62012 54.364844 34.722751 83.036713 65.814974 100.723906 97.372648 11.822492 21.03845 12.567216 39.098004 15.080659 58.926278 1.86181 13.591211 2.606534 21.503902 2.234171 36.026018a272.196581 272.196581 0 0 1-6.981786 44.683433c-17.035559 57.43683-26.716969 74.75166-41.332176 98.024282-14.894478 24.389707-33.512575 46.265972-55.295748 64.604797-33.047123 29.416594-46.824514 40.30818-71.586584 51.292858-22.341717 10.053772-53.992482 20.479907-116.363108 38.818733-52.316853 15.35993-127.627056 17.128649-181.247176 11.822491-26.716969-2.606534-83.129804-19.828274-95.697019-25.134431-18.338826-7.72651-34.722751-14.056663-50.920496-22.248626a937.235013 937.235013 0 0 1-105.657702-65.721883c-40.587452-28.858051-87.411966-76.334198-109.102049-99.51373-18.990459-20.293726-31.650765-37.701647-45.614338-56.226653-20.479907-27.368603-42.635443-59.577911-83.129804-128.464871v-0.09309z m435.849656-338.477007a23.831164 23.831164 0 0 0-37.050014-11.636311 70.562588 70.562588 0 0 0-26.437698 68.88696c4.282162 21.969355 12.753397 41.332176 25.786065 57.995373 14.801387 19.17664 35.467475 34.908932 62.091354 47.196876 22.155536 10.239953 48.220872 6.888696 67.211331-8.564325a23.924255 23.924255 0 0 0-2.606534-38.818732 202.471807 202.471807 0 0 1-54.178663-48.407053 215.969927 215.969927 0 0 1-34.815841-66.652788z" fill="#1296db" p-id="6958"></path></svg>
                <span>{{ formatPriceDisplay(userBalance || 0) }}</span>
              </div> -->
            <!-- </el-col> -->
            <el-col >
              <div class="mobile-trade-balance">
                <svg t="1744176905853" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6957" width="20" height="20"><path d="M60.974268 623.892437A430.636588 430.636588 0 0 1 13.963573 508.087872c-7.074877-29.788956-15.35993-67.956055-13.684302-110.219135 2.513443-62.277535 8.005782-112.360217 40.401271-189.252958 79.685456-188.973686 246.689788-247.527602 395.634566-183.9468 148.758597 63.673892 87.132695 227.606238 279.271458 376.644106 53.061577 41.145995 52.130672 45.335067 89.087595 64.790978 36.863832 19.455912 73.541484 36.026018 101.282448 53.62012 54.364844 34.722751 83.036713 65.814974 100.723906 97.372648 11.822492 21.03845 12.567216 39.098004 15.080659 58.926278 1.86181 13.591211 2.606534 21.503902 2.234171 36.026018a272.196581 272.196581 0 0 1-6.981786 44.683433c-17.035559 57.43683-26.716969 74.75166-41.332176 98.024282-14.894478 24.389707-33.512575 46.265972-55.295748 64.604797-33.047123 29.416594-46.824514 40.30818-71.586584 51.292858-22.341717 10.053772-53.992482 20.479907-116.363108 38.818733-52.316853 15.35993-127.627056 17.128649-181.247176 11.822491-26.716969-2.606534-83.129804-19.828274-95.697019-25.134431-18.338826-7.72651-34.722751-14.056663-50.920496-22.248626a937.235013 937.235013 0 0 1-105.657702-65.721883c-40.587452-28.858051-87.411966-76.334198-109.102049-99.51373-18.990459-20.293726-31.650765-37.701647-45.614338-56.226653-20.479907-27.368603-42.635443-59.577911-83.129804-128.464871v-0.09309z m435.849656-338.477007a23.831164 23.831164 0 0 0-37.050014-11.636311 70.562588 70.562588 0 0 0-26.437698 68.88696c4.282162 21.969355 12.753397 41.332176 25.786065 57.995373 14.801387 19.17664 35.467475 34.908932 62.091354 47.196876 22.155536 10.239953 48.220872 6.888696 67.211331-8.564325a23.924255 23.924255 0 0 0-2.606534-38.818732 202.471807 202.471807 0 0 1-54.178663-48.407053 215.969927 215.969927 0 0 1-34.815841-66.652788z" fill="#1296db" p-id="6958"></path></svg>
                <span>&nbsp;&nbsp;{{ formatPriceDisplay(tradeBalance || 0) }}</span>
                <el-button type="text" class="sync-account-btn" @click="syncTradeAccount" :loading="syncAccountLoading">
                  <el-icon v-if="!syncAccountLoading">
                    <Refresh />
                  </el-icon>
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </div>

      <!-- 搜索区域 -->
      <SearchSection
      :search-form="searchForm"
      :item-types="itemTypes"
      :nature-options="tradeConfig.petCharacter"
      :ability-options="tradeConfig.petSpecialCharacter"
      :loading="loading"
      :user-balance="userBalance"
      :trade-balance="tradeBalance"
      :sync-account-loading="syncAccountLoading"
      :format-price-display="formatPriceDisplay"
      :handle-search="handleSearch"
      :reset-search="resetSearch"
      :sync-trade-account="syncTradeAccount"
    ></SearchSection>


      <!-- 物品列表区域 -->
      <div v-if="!isMobile" class="items-section">
        <div class="section-title">
          <span class="title-icon"></span>
          <h3>交易市场</h3>
          <span class="title-count">共 {{ total }} 件商品</span>
        </div>

        <el-row :gutter="16">
          <el-col v-for="item in items" :key="item.id" :xs="12" :sm="8" :md="6" :lg="3" :xl="3"
            @mouseenter="(event) => openItemDetail (item, event)" @mouseleave="hideItemDetail">
            <div class="item-card" @click="showPriceChart(item, $event)">
              <!-- 左上角标签组 - 仅为精灵类型显示 -->
              <div v-if="item.type === 'pet'" class="left-corner-tags">
                <el-tag size="small" type="warning" class="level-tag">Lv.{{ item.description.level || 0 }}</el-tag>
                <el-tag size="small" type="success" class="iv-tag">个体:{{ item.description.iv || 0 }}</el-tag>
                <el-tag size="small" type="danger" class="nature-tag">{{ item.description.nature || '无' }}</el-tag>

                <el-tag size="small" style="background-color: #626aef; border-color: #626aef; color: #fff;"
                  v-if="item.description.isShiny==true">{{ '异色' }}</el-tag>
              </div>

              <div class="item-badge" :class="getTypeClass(item.type)">
                {{ getTypeLabel(item.type) }}
              </div>

              <div class="item-image">
                <!-- 从"cover"改为"contain"，确保图片完整显示 -->
                <el-image :src="item.type == 'pet'?`/pet/${item.id}.png`: `/item/${item.id}.png`" fit="contain">
                  <template #error>
                    <div class="image-error">
                      <el-image :src="item.image"/>
                    </div>
                  </template>
                </el-image>
              </div>
              <div class="item-info">
                <div class="item-name-row">
                  <h3 class="item-name">{{ item.name }}</h3>
                  <div class="item-stock">
                    <el-tooltip content="当前在售数量" placement="top">
                      <span class="stock-tag">
                        <el-icon>
                          <Goods />
                        </el-icon>
                        <span>{{ getStockCount(item) }}</span>
                      </span>
                    </el-tooltip>
                  </div>
                </div>
                <div class="item-price">
                  <svg t="1744176905853" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6957" width="16" height="16"><path d="M60.974268 623.892437A430.636588 430.636588 0 0 1 13.963573 508.087872c-7.074877-29.788956-15.35993-67.956055-13.684302-110.219135 2.513443-62.277535 8.005782-112.360217 40.401271-189.252958 79.685456-188.973686 246.689788-247.527602 395.634566-183.9468 148.758597 63.673892 87.132695 227.606238 279.271458 376.644106 53.061577 41.145995 52.130672 45.335067 89.087595 64.790978 36.863832 19.455912 73.541484 36.026018 101.282448 53.62012 54.364844 34.722751 83.036713 65.814974 100.723906 97.372648 11.822492 21.03845 12.567216 39.098004 15.080659 58.926278 1.86181 13.591211 2.606534 21.503902 2.234171 36.026018a272.196581 272.196581 0 0 1-6.981786 44.683433c-17.035559 57.43683-26.716969 74.75166-41.332176 98.024282-14.894478 24.389707-33.512575 46.265972-55.295748 64.604797-33.047123 29.416594-46.824514 40.30818-71.586584 51.292858-22.341717 10.053772-53.992482 20.479907-116.363108 38.818733-52.316853 15.35993-127.627056 17.128649-181.247176 11.822491-26.716969-2.606534-83.129804-19.828274-95.697019-25.134431-18.338826-7.72651-34.722751-14.056663-50.920496-22.248626a937.235013 937.235013 0 0 1-105.657702-65.721883c-40.587452-28.858051-87.411966-76.334198-109.102049-99.51373-18.990459-20.293726-31.650765-37.701647-45.614338-56.226653-20.479907-27.368603-42.635443-59.577911-83.129804-128.464871v-0.09309z m435.849656-338.477007a23.831164 23.831164 0 0 0-37.050014-11.636311 70.562588 70.562588 0 0 0-26.437698 68.88696c4.282162 21.969355 12.753397 41.332176 25.786065 57.995373 14.801387 19.17664 35.467475 34.908932 62.091354 47.196876 22.155536 10.239953 48.220872 6.888696 67.211331-8.564325a23.924255 23.924255 0 0 0-2.606534-38.818732 202.471807 202.471807 0 0 1-54.178663-48.407053 215.969927 215.969927 0 0 1-34.815841-66.652788z" fill="#1296db" p-id="6958"></path></svg>
                  <span>{{ formatPriceDisplay(item.price) }}</span>
                </div>
                <div class="item-seller">
                  <el-avatar :size="24"
                    src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"></el-avatar>
                  <span>{{ item.seller }}</span>
                </div>
                <el-button type="primary" @click="handleBuy(item)" :loading="loading" class="buy-button">
                  立即购买
                </el-button>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- 空状态显示 -->
        <el-empty v-if="items.length === 0" description="暂无商品，请尝试其他搜索条件" :image-size="200" />

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination v-if="!isMobile" v-model:current-page="currentPage" v-model:page-size="pageSize"
          :page-size="80" :total="total" layout="total, prev, pager, next, jumper"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" background />
          <!-- 移动端显示简化分页 -->
          <div v-else class="mobile-pagination">
            <div class="mobile-pagination-info">
              <span>共 {{ total }} 条记录</span>
              <span>{{ currentPage }} / {{ Math.ceil(total/pageSize )}}</span>
            </div>

            <div class="mobile-pagination-actions">
              <el-button :disabled="currentPage <= 1" @click="handleCurrentChange(currentPage - 1)"
                class="mobile-page-btn" plain>
                上一页
              </el-button>

              <!-- <select 
                v-model="pageSize" 
                @change="handleSizeChange" 
                class="mobile-page-size"
                style="height: 32px; border: 1px solid #dcdfe6; border-radius: 4px; padding: 0 8px; background-color: #fff; font-size: 14px; color: #606266; margin: 0 8px;"
              >
                <option :value="80">80条/页</option>
                <option :value="120">120条/页</option>
                <option :value="160">160条/页</option>
                <option :value="200">200条/页</option>
              </select> -->

              <el-button :disabled="currentPage >= Math.ceil(total/pageSize )" @click="handleCurrentChange(currentPage + 1)"
                class="mobile-page-btn" plain>
                下一页
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <div v-else>
        <MobileItemList
          ref="itemListRef"
          :items="items"
          :total="total"
          :loading="isLoading"
          @buy="handleBuy"
        />
        <div class="pagination-container">
          <!-- 移动端显示简化分页 -->
          <div class="mobile-pagination">
            <div class="mobile-pagination-info">
              <span>共 {{ total }} 条记录</span>
              <span>{{ currentPage }} / {{ Math.ceil(total/pageSize )}}</span>
            </div>

            <div class="mobile-pagination-actions">
              <el-button :disabled="currentPage <= 1" @click="handleCurrentChange(currentPage - 1)"
                class="mobile-page-btn" plain>
                上一页
              </el-button>

              <el-select v-model="pageSize" @change="handleSizeChange" class="mobile-page-size"
                size="small">
                <el-option :value="80" label="80条/页" />
                <el-option :value="120" label="120条/页" />
                <el-option :value="160" label="160条/页" />
                <el-option :value="200" label="200条/页" />
              </el-select>

              <el-button :disabled="currentPage >= Math.ceil(total/pageSize )" @click="handleCurrentChange(currentPage + 1)"
                class="mobile-page-btn" plain>
                下一页
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 浮动上架按钮 -->
  <el-button type="primary" size="large" round class="floating-add-btn" @click="openListItemDialog">
    <el-icon>
      <Goods />
    </el-icon>
    <h4>我的背包</h4>
  </el-button>

  <!-- 我的背包对话框（PC端） -->
  <el-dialog v-model="listItemDialogVisible" width="800px" destroy-on-close @close="handleListItemDialogClose">
    <template #header>
      <div class="dialog-header-tabs">
        <el-tabs v-model="activeTab" class="header-tabs">
          <el-tab-pane name="myBag">
            <template #label>
              <span>我的背包</span>
            </template>
          </el-tab-pane>
          <el-tab-pane name="myTrade">
            <template #label>
              <span>我的上架</span>
            </template>
          </el-tab-pane>
          <el-tab-pane name="tradeRecord">
            <template #label>
              <span>交易记录</span>
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>
    </template>
    <div class="list-item-container" v-loading="dialogLoading" element-loading-text="加载中...">
      <div v-if="activeTab === 'myBag'" class="tab-content" style="display: flex">
          <!-- 左侧：背包物品列表 -->
          <div class="inventory-section">
            <div class="section-header">
              <!-- 物品搜索框 -->
              <div class="inventory-search-section" style="margin-bottom: 10px;">
                <div style="position: relative; width: 220px;">
                  <input
                    ref="inventorySearchInputRef"
                    type="text"
                    v-model="inventorySearchInput"
                    placeholder="输入物品名称或ID搜索后添加"
                    @input="handleInventoryInputChange"
                    @compositionstart="handleCompositionStart"
                    @compositionend="handleCompositionEnd"
                    @focus="handleInputFocus"
                    style="width: 100%; padding: 8px 32px 8px 12px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;"
                    :disabled="inventoryItemSearchLoading"
                  />
                  
                  <!-- 清除按钮 -->
                  <button
                    v-if="inventorySearchInput"
                    @click="clearInventorySearch"
                    type="button"
                    style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); background: none; border: none; cursor: pointer; color: #909399; font-size: 16px; padding: 0; width: 16px; height: 16px; display: flex; align-items: center; justify-content: center;"
                    title="清除搜索"
                  >
                    ×
                  </button>
                  
                  <!-- 搜索结果下拉列表 -->
                  <div 
                    v-show="showInventorySearchResults" 
                    class="native-select-dropdown"
                    style="position: absolute; top: 100%; left: 0; right: 0; background: white; border: 1px solid #dcdfe6; border-top: none; border-radius: 0 0 4px 4px; max-height: 200px; overflow-y: auto; z-index: 1000;"
                  >
                    <!-- 加载状态 -->
                    <div v-if="inventoryItemSearchLoading || isInventoryUserTyping" class="search-loading-container" style="padding: 12px; text-align: center;">
                      <span>正在搜索物品...</span>
                    </div>
                    
                    <!-- 无结果状态 -->
                    <div v-else-if="hasInventorySearched && inventoryItemSearchResults.length === 0" style="padding: 12px; text-align: center; color: #909399;">
                      未找到相关物品
                    </div>
                    
                    <!-- 默认提示 -->
                    <div v-else-if="!hasInventorySearched" style="padding: 12px; text-align: center; color: #909399;">
                      请输入物品名称或ID进行搜索
                    </div>
                    
                    <!-- 搜索结果选项 -->
                    <div 
                      v-for="item in inventoryItemSearchResults"
                      :key="item.id"
                      @click="selectInventorySearchItem(item)"
                      style="padding: 8px 12px; cursor: pointer; border-bottom: 1px solid #f5f7fa;"
                      @mouseover="$event.target.style.backgroundColor = '#f5f7fa'"
                      @mouseout="$event.target.style.backgroundColor = 'white'"
                    >
                      <div style="display: flex; justify-content: space-between;">
                        <span style="margin-right: 15px;">{{ item.name }}</span>
                        <span style="color: #8492a6; font-size: 13px;">ID: {{ item.id }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="inventory-type-filter">
                <el-radio-group v-model="inventoryTypeFilter" @change="handleInventoryTypeChange" size="small">
                  <el-radio-button value="all">全部</el-radio-button>
                  <el-radio-button value="1">精灵</el-radio-button>
                  <el-radio-button value="2">道具</el-radio-button>
                  <el-radio-button value="3">时装</el-radio-button>
                </el-radio-group>
              </div>
            </div>

            <div class="inventory-list" ref="inventoryListRef">
              <el-empty v-if="inventoryItems.length === 0" description="暂无可上架物品"></el-empty>

              <!-- 精灵卡片中的详细内容 -->
              <div v-for="item in inventoryItems"
                :key="item.id + '-' + (item.type === 'pet' ? item.catchTime : 0)" class="inventory-item"
                :class="{ 'inventory-item-selected': isItemSelected(item) }" @click="selectInventoryItem(item)">
                <!-- 添加闪光五角星标记 -->
                <el-icon v-if="item.isShiny" class="shiny-star">
                  <Star />
                </el-icon>

                <div class="inventory-item-content">
                  <!-- 左侧：图片和基本信息 -->
                  <div class="inventory-item-left">
                    <el-image :src="item.image" fit="contain" class="inventory-item-image"></el-image>
                    <div class="inventory-item-info" v-if="item.type === 'pet'">
                      <div class="inventory-item-name">
                        {{ item.name }}
                      </div>
                      <div class="inventory-item-type">
                        <el-tag size="small" :type="getTagType(item.type)">{{ getTypeLabel(item.type) }}</el-tag>
                      </div>
                    </div>
                  </div>

                  <!-- 右侧：属性详情 -->
                  <template v-if="item.type === 'pet'">
                    <div class="pet-attributes-flex">
                      <!-- 第一行：基本属性 -->
                      <div class="attr-row">
                        <div class="attr-item primary">
                          <span class="attr-label">等级</span>
                          <span class="attr-value level">{{ item.level || 0 }}</span>
                        </div>
                        <div class="attr-item primary">
                          <span class="attr-label">个体</span>
                          <span class="attr-value" :class="getIvClass(item.iv)">{{ item.iv || 0 }}</span>
                        </div>
                        <div class="attr-item primary">
                          <span class="attr-label">性格</span>
                          <span class="attr-value">{{ item.nature || '暂无' }}</span>
                        </div>
                        <div class="attr-item primary">
                          <span class="attr-label">特性</span>
                          <span class="attr-value ability">{{ item.ability || '暂无' }}</span>
                        </div>
                        <div class="attr-item primary">
                          <span class="attr-label">额HP</span>
                          <span class="attr-value addMaxHP">{{ item.addMaxHP || 0}}</span>
                        </div>
                      </div>

                      <!-- 第二行：学习力属性 -->
                      <div class="attr-row">
                        <div class="attr-item ev">
                          <span class="attr-label">HP</span>
                          <span class="attr-value">{{ item.evHp || 0 }}</span>
                        </div>
                        <div class="attr-item ev">
                          <span class="attr-label">攻击</span>
                          <span class="attr-value">{{ item.evAtk || 0 }}</span>
                        </div>
                        <div class="attr-item ev">
                          <span class="attr-label">防御</span>
                          <span class="attr-value">{{ item.evDef || 0 }}</span>
                        </div>
                        <div class="attr-item ev">
                          <span class="attr-label">特攻</span>
                          <span class="attr-value">{{ item.evSa || 0 }}</span>
                        </div>
                        <div class="attr-item ev">
                          <span class="attr-label">特防</span>
                          <span class="attr-value">{{ item.evSd || 0 }}</span>
                        </div>
                        <div class="attr-item ev">
                          <span class="attr-label">速度</span>
                          <span class="attr-value">{{ item.evSp || 0 }}</span>
                        </div>
                      </div>
                    </div>
                  </template>

                  <!-- 道具显示 - 优化名称显示的布局 -->
                  <template v-if="item.type === 'item'">
                    <div class="item-display">
                      <!-- 将名称移到右侧顶部，给予更多显示空间 -->
                      <div class="item-header">
                        <div class="item-name-container">
                          <h4 class="item-title">{{ item.name }}</h4>
                          <el-tag size="small" type="success" effect="plain">道具</el-tag>
                        </div>
                        <div class="item-quantity-badge">
                          <span>x{{ item.maxQuantity || 0 }}</span>
                        </div>
                      </div>
                      <div class="item-description">
                        {{ item.description || getDefaultItemDescription(item.name) }}
                      </div>
                    </div>
                  </template>

                  <!-- 时装显示 - 添加紫色主题风格 -->
                  <template v-if="item.type === 'fashion'">
                    <div class="item-display fashion-display">
                      <div class="item-header">
                        <div class="item-name-container">
                          <h4 class="item-title">{{ item.name }}</h4>
                          <el-tag size="small" class="fashion-tag">时装</el-tag>
                        </div>
                        <div class=" fashion-quantity">
                          <span>x{{ item.maxQuantity || 0 }}</span>
                        </div>
                      </div>
                      <div class="item-description fashion-description">
                        {{ item.description || "华丽的时装，穿上它将展现你的独特魅力" }}
                      </div>
                    </div>
                  </template>
                </div>
              </div>
              
              <!-- 滚动加载状态 -->
              <div v-if="inventoryScrollLoading" class="inventory-scroll-loading">
                <div class="loading-text">
                  <el-icon class="is-loading"><Loading /></el-icon>
                  正在加载更多...
                </div>
              </div>
              
              <!-- 没有更多数据提示 -->
              <div v-if="!inventoryHasMore && inventoryItems.length > 0" class="inventory-scroll-loading">
                <div class="no-more-text">已加载全部物品</div>
              </div>
              

            </div>
          </div>

          <!-- 右侧：上架详情 -->
          <div class="listing-section">
            <div class="section-header">
              <h3>上架详情</h3>
            </div>

            <div v-if="!selectedInventoryItem" class="no-item-selected">
              <el-empty description="请从左侧选择要上架的物品"></el-empty>
            </div>

            <div v-else class="listing-details">
              <div class="item-preview">
                <el-image :src="selectedInventoryItem.image" fit="contain" class="preview-image"></el-image>
                <div class="preview-details">
                  <h3 class="preview-name">{{ selectedInventoryItem.name }}</h3>
                  <div class="preview-tags">
                    <el-tag :type="getTagType(selectedInventoryItem.type)" size="small" :color="selectedInventoryItem.type == 'fashion' ? '#8e44ad' : ''" effect="dark">
                      {{ getTypeLabel(selectedInventoryItem.type) }}
                    </el-tag>
                    <!-- 添加闪光标签 -->
                    <el-tag type="warning" v-if="selectedInventoryItem.isShiny">异色</el-tag>
                  </div>

                  <!-- 精灵详情 -->
                  <template v-if="selectedInventoryItem.type === 'pet'">
                    <div class="preview-pet-info">
                      <div class="pet-info-row">
                        <div class="pet-info-item">
                          <span class="pet-info-label">等级</span>
                          <span class="pet-info-value level">Lv.{{ selectedInventoryItem.level || 0 }}</span>
                        </div>
                        <div class="pet-info-item">
                          <span class="pet-info-label">个体</span>
                          <span class="pet-info-value iv" :class="getIvClass(selectedInventoryItem.iv)">
                            {{ selectedInventoryItem.iv || 0 }}
                          </span>
                        </div>
                      </div>
                    </div>
                  </template>

                  <!-- 道具详情 -->
                  <template v-else-if="selectedInventoryItem.type === 'item'">
                    <div class="preview-item-info">
                      <div class="item-info-row">
                        <div class="item-info-item">
                          <span class="item-info-label">库存数量</span>
                          <span class="item-info-value quantity">
                            {{ selectedInventoryItem.maxQuantity || 0 }}
                          </span>
                        </div>
                      </div>
                    </div>
                  </template>

                  <template v-else-if="selectedInventoryItem.type === 'fashion'">
                    <div class="preview-item-info">
                      <div class="item-info-row">
                        <div class="item-info-item">
                          <span class="item-info-label">库存数量</span>
                          <span class="item-info-value quantity">
                            {{ selectedInventoryItem.maxQuantity || 0 }}
                          </span>
                        </div>
                      </div>
                    </div>
                  </template>

                  <!-- 默认描述 -->
                  <template v-else>
                    <p class="preview-description">{{ selectedInventoryItem.description || "暂无描述" }}</p>
                  </template>
                </div>
              </div>

              <el-form label-position="top" class="listing-form">
                <el-form-item label="上架价格" required>
                  <el-input-number v-model="listItemForm.price" :precision="0" controls-position="right"
                    style="width: 100%"></el-input-number>
                  <!-- 设置精度为0，只允许整数 -->
                  <div class="price-hint">
                    <span>系统将收取5%手续费</span>
                    <span>预计收入: <span class="expected-income">{{ formatXINBean(calculateExpectedIncome()) }}</span></span>
                  </div>
                </el-form-item>

                <el-form-item label="上架数量" v-if="canSetQuantity">
                  <el-input-number v-model="listItemForm.quantity" :min="1"
                    :max="selectedInventoryItem?.maxQuantity || 1" @change="validateQuantity" controls-position="right"
                    style="width: 100%"></el-input-number>
                </el-form-item>
              </el-form>

              <!-- 空白占位，确保按钮在底部 -->
              <!-- <div class="flex-spacer"></div> -->

              <!-- 按钮固定在底部 -->
              <div class="listing-actions">
                <el-button plain @click="resetListingForm">重置</el-button>
                <el-button type="primary" @click="confirmListItem" :loading="listItemLoading"
                  :disabled="!canSubmitListing">上架</el-button>
              </div>
            </div>
          </div>
       </div>
       <div v-if="activeTab === 'myTrade'" class="tab-content">
          <!-- 现有的表格和内容 -->
          <el-table v-if="myListedItems.length > 0" :data="myListedItems" style="width: 100%"
            :row-class-name="tableRowClassName">
            <el-table-column prop="image" label="物品" width="80">
              <template #default="scope">
                <!-- 为每个单元格添加tooltip提示 -->
                <el-tooltip :content="scope.row.itemDesc || getDefaultItemDescription(scope.row.name)"
                  placement="top-start" :effect="'light'" :max-width="300">
                  <el-image :src="scope.row.image" style="width: 50px; height: 50px" fit="contain"></el-image>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="名称">
              <template #default="scope">
                <!-- 为名称列添加tooltip -->
                <el-tooltip :content="scope.row.itemDesc || getDefaultItemDescription(scope.row.name)" placement="top"
                  :effect="'light'" :max-width="300">
                  <span>{{ scope.row.name }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="类型">
              <template #default="scope">
                <el-tag :type="getTagType(scope.row.type)" :color="scope.row.type == 'fashion' ? '#8e44ad' : ''" effect="dark">{{ getTypeLabel(scope.row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100">
              <template #default="scope">
                <span class="quantity-text">{{ scope.row.quantity || 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格">
              <template #default="scope">
                <span class="price-text">{{ formatPriceDisplay(scope.row.price) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="listTime" label="上架时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.listTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="danger" link @click="confirmRemoveItem(scope.row)">
                  下架
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 无数据提示 -->
          <el-empty v-else description="你还没有上架物品" />
       </div>
       <div v-if="activeTab === 'tradeRecord'" class="tab-content">
          <div class="history-container">
            <!-- 查询筛选区域 -->
            <div class="history-filter">
              <el-form :inline="true" :model="historyForm">
                <el-form-item label="类型">
                  <select 
                    style="width: 90px; height: 32px; border: 1px solid #dcdfe6; border-radius: 4px; padding: 0 8px; background-color: #fff; font-size: 14px; color: #606266; cursor: pointer;" 
                    v-model="historyForm.type"
                  >
                    <option value="">全部</option>
                    <option value="buy">购买</option>
                    <option value="sell">出售</option>
                  </select>
                </el-form-item>
                <el-form-item label="时间">
                  <el-date-picker v-model="historyForm.dateRange" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                    style="width: 230px;" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="searchHistory" :loading="historyLoading">
                    <el-icon>
                      <Search />
                    </el-icon> 查询
                  </el-button>
                  <el-button @click="resetHistorySearch">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 交易记录表格 -->
            <el-table :data="tradeHistory" style="width: 100%" row-class-name="history-row" :empty-text="'暂无交易记录'"
              v-loading="historyLoading">
              <el-table-column prop="orderId" label="订单号">
                <template #default="scope">
                  <div class="order-id-cell">{{ scope.row.orderId }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="item" label="物品信息">
                <template #default="scope">
                  <el-tooltip :content="scope.row.itemDesc">
                    <div class="history-item">
                      <el-image :src="scope.row.image" fit="cover" class="history-item-image"></el-image>
                      <div class="history-item-info">
                        <div class="history-item-name">{{ scope.row.itemName }}</div>
                        <el-tag size="small" :type="getTagType(scope.row.itemType)" :color="scope.row.itemType == 'fashion' ? '#8e44ad' : ''" effect="dark">
                          {{ getTypeLabel(scope.row.itemType) }}
                        </el-tag>
                      </div>
                    </div>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column prop="type" label="交易类型" align="center">
                <template #default="scope">
                  <el-tag :type="scope.row.type === 'buy' ? 'success' : 'danger'" effect="plain">
                    {{ scope.row.type === 'buy' ? '购买' : '出售' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="交易价格">
                <template #default="scope">
                  <span class="price-text" :class="{'price-negative': scope.row.type === 'buy'}">
                    {{ scope.row.type === 'buy' ? '-' : '' }}{{ formatPriceDisplay(scope.row.price) }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="time" label="交易时间">
                <template #default="scope">
                  {{ formatDateTime(scope.row.time) }}
                </template>
              </el-table-column>
            </el-table>

          </div>
       </div>
    </div>
    
    <!-- Dialog Footer: 交易记录分页 -->
    <template #footer v-if="activeTab === 'tradeRecord'">
      <div class="dialog-footer-pagination">
        <el-pagination v-model:current-page="historyPage" v-model:page-size="historyPageSize"
          :page-sizes="[10, 20, 30, 50]" :total="historyTotal" layout="total, prev, pager, next, jumper"
          @size-change="handleHistorySizeChange" @current-change="handleHistoryPageChange" background />
      </div>
    </template>
  </el-dialog>

  <!-- 移动端背包组件 -->
  <mobile-bag 
    :show-dialog="mobileBagVisible"
    @update:showDialog="mobileBagVisible = $event"
    @item-updated="handleSearch"
    :list="currentDetailItem"
  />

  <!-- 商品详情悬浮卡片 -->
  <div v-if="currentDetailItem" class="item-detail-card" :style="{
      left: `${detailCardPosition.x}px`,
      top: `${detailCardPosition.y}px`
    }">
    <div class="detail-card-header">
      <div class="detail-card-image">
        <el-image :src="currentDetailItem.image" fit="contain"></el-image>
        <span v-if="currentDetailItem.description.isShiny" class="shiny-tag">
          异色
        </span>
      </div>
      <div class="detail-card-title">
        <h3>{{ currentDetailItem.name }}</h3>
        <el-tag :type="getTagType(currentDetailItem.type)" size="small">
          {{ getTypeLabel(currentDetailItem.type) }}
        </el-tag>
      </div>
    </div>

    <div class="detail-card-content">
      <!-- 通用信息 -->
      <div class="detail-info-row">
        <div class="detail-info-item">
          <span class="info-label">价格</span>
          <span class="info-value price">
            <svg t="1744176905853" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6957" width="16" height="16"><path d="M60.974268 623.892437A430.636588 430.636588 0 0 1 13.963573 508.087872c-7.074877-29.788956-15.35993-67.956055-13.684302-110.219135 2.513443-62.277535 8.005782-112.360217 40.401271-189.252958 79.685456-188.973686 246.689788-247.527602 395.634566-183.9468 148.758597 63.673892 87.132695 227.606238 279.271458 376.644106 53.061577 41.145995 52.130672 45.335067 89.087595 64.790978 36.863832 19.455912 73.541484 36.026018 101.282448 53.62012 54.364844 34.722751 83.036713 65.814974 100.723906 97.372648 11.822492 21.03845 12.567216 39.098004 15.080659 58.926278 1.86181 13.591211 2.606534 21.503902 2.234171 36.026018a272.196581 272.196581 0 0 1-6.981786 44.683433c-17.035559 57.43683-26.716969 74.75166-41.332176 98.024282-14.894478 24.389707-33.512575 46.265972-55.295748 64.604797-33.047123 29.416594-46.824514 40.30818-71.586584 51.292858-22.341717 10.053772-53.992482 20.479907-116.363108 38.818733-52.316853 15.35993-127.627056 17.128649-181.247176 11.822491-26.716969-2.606534-83.129804-19.828274-95.697019-25.134431-18.338826-7.72651-34.722751-14.056663-50.920496-22.248626a937.235013 937.235013 0 0 1-105.657702-65.721883c-40.587452-28.858051-87.411966-76.334198-109.102049-99.51373-18.990459-20.293726-31.650765-37.701647-45.614338-56.226653-20.479907-27.368603-42.635443-59.577911-83.129804-128.464871v-0.09309z m435.849656-338.477007a23.831164 23.831164 0 0 0-37.050014-11.636311 70.562588 70.562588 0 0 0-26.437698 68.88696c4.282162 21.969355 12.753397 41.332176 25.786065 57.995373 14.801387 19.17664 35.467475 34.908932 62.091354 47.196876 22.155536 10.239953 48.220872 6.888696 67.211331-8.564325a23.924255 23.924255 0 0 0-2.606534-38.818732 202.471807 202.471807 0 0 1-54.178663-48.407053 215.969927 215.969927 0 0 1-34.815841-66.652788z" fill="#1296db" p-id="6958"></path></svg>
            {{ formatPriceDisplay(currentDetailItem.price) }}
          </span>
        </div>
        <div class="detail-info-item">
          <span class="info-label">卖家</span>
          <span class="info-value seller">
            <el-avatar :size="24" src="https://robohash.org/10.png"></el-avatar>
            {{ currentDetailItem.seller }}
          </span>
        </div>
      </div>

      <!-- 精灵详情 -->
      <template v-if="currentDetailItem.type === 'pet'">
        <div class="detail-pet-info">
          <div class="pet-info-row">
            <div class="pet-info-item">
              <span class="info-label">等级</span>
              <span class="info-value level">
                Lv.{{ currentDetailItem.description.level || '?' }}
              </span>
            </div>
            <div class="pet-info-item">
              <span class="info-label">个体</span>
              <span class="info-value iv" :class="getIvClass(currentDetailItem.description.iv)">
                {{ currentDetailItem.description.iv || 0 }}
              </span>
            </div>
          </div>

          <div class="pet-stats">
            <div class="stat-item">
              <span class="stat-label">性格</span>
              <span class="stat-value">{{ currentDetailItem.description.nature || '未知' }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">特性</span>
              <span class="stat-value">{{ currentDetailItem.description.ability || '无特性' }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">额HP</span>
              <span class="stat-value">{{ currentDetailItem.description.addMaxHP || 0 }}</span>
            </div>
          </div>
          <div class="pet-stats" style="margin-top: 10px;">
            <div class="stat-item">
              <span class="stat-label">HP</span>
              <span class="stat-value">{{ currentDetailItem.description.evHp || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">攻击</span>
              <span class="stat-value">{{ currentDetailItem.description.evAtk || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">防御</span>
              <span class="stat-value">{{ currentDetailItem.description.evDef || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">特攻</span>
              <span class="stat-value">{{ currentDetailItem.description.evSa || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">特防</span>
              <span class="stat-value">{{ currentDetailItem.description.evSd || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">速度</span>
              <span class="stat-value">{{ currentDetailItem.description.evSp || 0 }}</span>
            </div>
          </div>
        </div>
      </template>

      <!-- 道具详情 -->
      <template v-else-if="currentDetailItem.type === 'item'">
        <div class="detail-item-info">
          <div class="item-info-row">
            <div class="item-info-item">
              <span class="info-label">数量</span>
              <span class="info-value quantity">
                {{ currentDetailItem.quantity || 0 }}
              </span>
            </div>
            <div class="item-info-item">
              <span class="info-label">描述</span>
              <span class="info-value description">
                {{ '一个神奇的XIN计划道具' }}
              </span>
            </div>
          </div>
        </div>
      </template>
            <!-- 价格走势图 -->
      <div class="price-chart-section">
        <h4 class="section-title">近7日价格走势</h4>
        <div ref="detailChartContainer" class="detail-chart-container"></div>
      </div>
    </div>
  </div>

  <!-- 购买数量选择对话框 -->
  <el-dialog v-model="buyQuantityDialogVisible" :title="`购买 ${currentBuyItem?.name || '物品'}`" width="400px"
    destroy-on-close class="buy-quantity-dialog">
    <div class="buy-item-container">
      <!-- 物品信息 -->
      <div class="buy-item-info">
        <el-image :src="currentBuyItem?.image" fit="contain" class="buy-item-image"></el-image>
        <div class="buy-item-details">
          <h3 class="buy-item-name">{{ currentBuyItem?.name }}</h3>
          <div class="buy-item-type">
            <el-tag size="small" :type="getTagType(currentBuyItem?.type)">
              {{ getTypeLabel(currentBuyItem?.type) }}
            </el-tag>
          </div>
          <div class="buy-item-price">
            <span class="price-label">单价:</span>
            <span class="price-value">{{ formatXINBean(currentBuyItem?.price) }}</span>
          </div>
          <div class="buy-item-stock">
            <span class="stock-label">库存:</span>
            <span class="stock-value">{{ getStockCount(currentBuyItem) }} 个</span>
          </div>
        </div>
      </div>

      <!-- 数量选择 -->
      <div class="buy-quantity-section">
        <div class="quantity-label">购买数量:</div>
        <div class="quantity-control">
          <el-input-number v-model="buyQuantity" :min="1" :max="currentBuyItem ? getStockCount(currentBuyItem) : 1"
            size="large" controls-position="right"></el-input-number>
        </div>
      </div>

      <!-- 总价 -->
      <div class="buy-total-price">
        <span class="total-label">总价:</span>
        <span class="total-value">{{ formatXINBean(calculateTotalPrice()) }}</span>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="buyQuantityDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBuy" :loading="loading">
          确认购买
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 二级密码验证对话框 -->
<!-- <template> -->
  <el-dialog v-model="secondaryPasswordVisible" title="安全验证" width="400px">
    <div class="secondary-password-container">
      <p class="verification-message">为保障您的账户安全，请输入二级密码进行验证</p>
      <el-form :model="secondaryPasswordForm" ref="secondaryPasswordFormRef">
        <el-form-item prop="password">
          <el-input
            v-model="secondaryPasswordForm.password"
            type="password"
            show-password
            placeholder="请输入6位数字二级密码"
            maxlength="6"
          />
        </el-form-item>
        <div class="verification-actions">
          <el-button @click="secondaryPasswordVisible = false">取消</el-button>
          <el-button type="primary" :loading="verificationLoading" @click="confirmSecondaryPassword">
            确认
          </el-button>
        </div>
      </el-form>
      <div class="verification-tip">
        <p>如您未设置二级密码，请前往个人资料-账号安全中设置</p>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed, watch, nextTick } from 'vue'
import { Search, Picture, Coin, Close, Plus, Goods, ArrowDown, ArrowUp, Star, Refresh, Wallet, Loading } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElButton, ElInput, ElCheckbox, ElInputNumber, ElForm, ElFormItem, ElSelect, ElOption } from 'element-plus'
// 导入 echarts
import * as echarts from 'echarts/core'
import { LineChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DataZoomComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { getTradeList, getUserItems, sellItem, getMyListingItems, removeListingItem, buyItem, getTradeRecords, syncTradeBalance } from '@/api/trade'
import { convertItemType, getItemImage, getNatureName, getSpecialAbility } from '@/utils/trade'
import { CURRENCY, formatXINBean } from '@/utils/currency.js'
import { getUserBalance, verifySecondaryPassword } from '@/api/user' // 导入获取用户余额的API
// 已移除 getItemInfo API 导入，改用本地 itemFinder 工具
import { formatPrice } from '@/utils/trade.js'
import { useWindowSize } from '@vueuse/core'
import { findItemNameById, findItemsByKeyword } from '@/utils/itemFinder.js';
import { isCEFBrowser } from '@/utils/index.js';
// 导入移动端背包组件
import MobileBag from './mobileBag.vue'
import MobileItemList from './components/MobileItemList.vue'
import SearchSection from './components/SearchSection.vue'
import tradeConfig from './trade.config'
// 注册 echarts 组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DataZoomComponent,
  LegendComponent,
  LineChart,
  BarChart,
  CanvasRenderer
])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  type: '',
  sort: 'time_desc',
  iv: 0,
  nature: '',
  ability: '',
  isShiny: false,
})

// 物品类型选项
const itemTypes = [
  { label: '全部', value: '' },
  { label: '精灵', value: 'pet' },
  { label: '时装', value: 'fashion' },
  { label: '道具', value: 'item' }
]

// 分页相关，修改默认值
const currentPage = ref(1)
const pageSize = ref(80)  // 修改默认值为30
const total = ref(100)  // 模拟总数据
const loading = ref(false)
const itemListRef = ref(null)

// 在mockItems数组中添加更多商品
const mockItems = []

// 物品列表数据
const items = ref([...mockItems])
const { width } = useWindowSize()
const isMobile = computed(() => width.value <= 768) // 判断是否为移动端

const getItemTypeCode = (type) => {
  switch(type) {
    case 'pet': return 1  // 精灵对应1
    case 'item': return 2  // 道具对应2
    case 'fashion': return 3  // 时装对应3
    default: return undefined
  }
}

const getTypeClass = (type) => {
  switch (type) {
    case 'pet': return 'badge-pet'  // 精灵
    case 'item': return 'badge-item'  // 道具
    case 'fashion': return 'badge-fashion'  // 时装
    default: return ''
  }
}

const itemTypeLabels = {
  'pet': '精灵',
  'item': '道具',
  'fashion': '时装'
}

const getOrderByCode = (sort) => {
  switch(sort) {
    case 'price_asc': return 'price_low'  // 从低到高改为price_low
    case 'price_desc': return 'price_high' // 从高到低改为price_high
    default: return undefined  // 最新上架不传参数
  }
}

// 修复变量重复声明问题
// 在文件顶部脚本区域只保留一个声明
let currentRequestId = 0;

// 统一使用这个变量进行请求追踪
const handleSearch = async () => {
  loading.value = true;
  globalLoading.value = true;
  
  // 生成新的请求ID
  const requestId = ++currentRequestId;
  
  try {
    // 构建搜索参数
    const params = {
      currentPage: currentPage.value,
      limit: Math.max(80, pageSize.value),
      keyword: searchForm.keyword || undefined,
      itemType: searchForm.type ? getItemTypeCode(searchForm.type) : undefined,
      iv: searchForm.iv ? searchForm.iv : undefined,
      nature: searchForm.nature ? searchForm.nature : undefined,
      ability: searchForm.ability ? searchForm.ability: undefined,
      isShiny: searchForm.isShiny == true ? searchForm.isShiny : undefined
    };
    
    if (searchForm.sort !== 'time_desc') {
      params.sort = getOrderByCode(searchForm.sort);
    }
    
    // 在发起API请求前将items清空
    items.value = [];
    
    const response = await getTradeList(params);
    
    // 检查这个响应是否来自最新请求
    if (requestId !== currentRequestId) {
      // 忽略旧请求的响应，但需要重置加载状态
      loading.value = false;
      globalLoading.value = false;
      return;
    }
    
    if (response.code === 200) {
      // 确保数据处理和UI更新同步
      await nextTick();
      
      // 使用新数组替换原数组，确保响应式系统能检测到变化
      const newItems = response.data.list.map(item => {
        let description;
        if (item.itemType !== 1) {
          description = item.itemDesc;
        } else {
          try {
            // 尝试解析JSON
            if (typeof item.itemDesc === 'string') {
              description = JSON.parse(item.itemDesc);
            } else if (typeof item.itemDesc === 'object') {
              description = item.itemDesc;
            } else {
              // 如果无法解析，提供一个默认对象
              description = {
                level: 0,
                iv: 0,
                nature: '未知',
                ability: '未知'
              };
            }
          } catch (error) {
            console.error('解析物品描述JSON失败:', error);
            description = {
              level: 0,
              iv: 0,
              nature: '未知',
              ability: '未知'
            };
          }
        }

        // 解析价格历史数据（假设后端在返回数据中包含priceHistory字段）
        let priceHistory = [];
        if (item.priceHistory) {
          try {
            // 尝试解析价格历史数据
            if (typeof item.priceHistory === 'string') {
              priceHistory = JSON.parse(item.priceHistory);
            } else if (Array.isArray(item.priceHistory)) {
              priceHistory = item.priceHistory;
            }
          } catch (error) {
            console.error('解析价格历史数据失败:', error);
          }
        }

        return {
          id: item.itemId,
          listId: item.listingId,
          name: item.itemName,
          price: item.unitPrice,
          seller: item.sellerAccount,
          type: convertItemType(item.itemType),
          image: getItemImage(item),
          quantity: item.quantity,
          description: description,
          priceHistory: priceHistory  // 保存价格历史数据
        };
      });
      
      // 使用新数组引用替换旧数组
      items.value = newItems;
      
      // 更新总数和分页
      total.value = response.data.totalCount;
      currentPage.value = response.data.currentPage;
      pageSize.value = response.data.pageSize;
      
    } else {
      ElMessage.error(response.msg || '获取交易列表失败');
    }
  } catch (error) {
    console.error('查询交易列表错误:', error);
    ElMessage.error('获取交易列表失败');
  } finally {
    loading.value = false;
    globalLoading.value = false;
  }
};

// 修改重置搜索函数，添加请求ID追踪
const resetSearch = () => {
  searchForm.keyword = '';
  searchForm.type = '';
  searchForm.sort = 'time_desc';
  searchForm.iv = 0;
  searchForm.nature = '';
  searchForm.ability = '';
  searchForm.isShiny = false;
  currentPage.value = 1;
  handleSearch(); // 使用已经修改过的handleSearch函数
};

// 修改页码变化处理函数，添加请求ID追踪
const handleCurrentChange = (page) => {
  currentPage.value = page;
  handleSearch();
};

// 修改每页条数变化处理函数，添加请求ID追踪
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  handleSearch();
};

const chartVisible = ref(false)
const chartPosition = ref({ top: '0px', left: '0px' })
const chartContainer = ref(null)
const currentItem = ref(null)
let priceChart = null

const showPriceChart = (item, event) => {
  currentItem.value = item
  
  // 计算弹出位置
  const rect = event.currentTarget.getBoundingClientRect()
  const chartWidth = 450 // 图表宽度
  const chartHeight = 380 // 图表高度，增加以容纳标题
  const windowWidth = window.innerWidth
  
  // 检查右侧是否有足够空间，如果没有，则显示在左侧
  let left
  if (rect.right + chartWidth + 20 > windowWidth) {
    // 右侧空间不足，显示在左侧
    left = Math.max(rect.left - chartWidth - 20, 10) + 'px'
  } else {
    // 右侧空间足够
    left = rect.right + 20 + 'px'
  }
  
  // 计算top位置，确保图表尽量居中对齐卡片
  let top = rect.top + window.scrollY + (rect.height / 2) - (chartHeight / 2)
  
  // 确保图表不会超出顶部
  top = Math.max(top, window.scrollY + 10)
  
 // 确保图表不会超出底部
  const maxTop = window.scrollY + window.innerHeight - chartHeight - 10
  top = Math.min(top, maxTop)
  
  chartPosition.value = {
    top: top + 'px',
    left: left
  }
  
  chartVisible.value = true
  
  // 延迟初始化图表，确保DOM已更新
  setTimeout(() => {
    initPriceChart(item)
  }, 0)
}


// 初始化价格走势图
const initPriceChart = (item) => {
  if (!chartContainer.value) return
  
  // 如果已存在图表实例，先销毁
  if (priceChart) {
    priceChart.dispose()
  }
  
  // 创建图表实例
  priceChart = echarts.init(chartContainer.value)
  
  // 使用真实价格历史数据
  const dates = []
  const prices = []
  const volumes = []
  
  // 如果有价格历史数据，则使用历史数据
  if (item.priceHistory && item.priceHistory.length > 0) {
    // 按日期排序
    const sortedHistory = [...item.priceHistory].sort((a, b) => {
      return new Date(a.date) - new Date(b.date)
    })
    
    // 提取日期和价格
    sortedHistory.forEach(record => {
      // 从 YYYY-MM-DD 格式转换为 MM月DD日 格式
      const dateObj = new Date(record.date)
      const month = dateObj.getMonth() + 1
      const day = dateObj.getDate()
      dates.push(`${month}月${day}日`)
      
      // 提取价格
      prices.push(record.price)
      
      // 价格历史中没有交易量，暂时设为1
      volumes.push(1)
    })
  } else {
    // 如果没有价格历史数据，显示当前价格
    const today = new Date()
    const month = today.getMonth() + 1
    const day = today.getDate()
    dates.push(`${month}月${day}日`)
    prices.push(item.price)
    volumes.push(1)
  }
  
  // 设置图表选项
  const option = {
    backgroundColor: '#fff',
    title: {
      show: true, // 显示标题
      text: item.name + ' 价格历史',
      subtext: item.priceHistory && item.priceHistory.length > 0 ? '真实历史数据' : '暂无历史数据',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      },
      subtextStyle: {
        fontSize: 12,
        color: '#999'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        shadowStyle: {
          color: 'rgba(0,0,0,0.05)'
        }
      },
      backgroundColor: 'rgba(255,255,255,0.95)',
      borderColor: '#eee',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      padding: [10, 15],
      // formatter: function(params) {
      //   // 自定义提示框内容
      //   const priceItem = params.find(item => item.seriesName === '价格')
      //   const volumeItem = params.find(item => item.seriesName === '交易量')
        
      //   let html = `<div style="font-weight: bold; margin-bottom: 5px;">${priceItem.axisValue}</div>`
        
      //   if (priceItem) {
      //     html += `<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 3px;">
      //       <span style="margin-right: 15px;">
      //         <span style="display: inline-block; width: 10px; height: 10px; background-color: ${priceItem.color}; border-radius: 50%; margin-right: 5px;"></span>
      //         价格:
      //       </span>
      //       <span style="font-weight: bold;">${priceItem.value} XIN豆</span>
      //     </div>`
      //   }
        
      //   if (volumeItem) {
      //     html += `<div style="display: flex; justify-content: space-between; align-items: center;">
      //       <span style="margin-right: 15px;">
      //         <span style="display: inline-block; width: 10px; height: 10px; background-color: ${volumeItem.color}; border-radius: 50%; margin-right: 5px;"></span>
      //         交易量:
      //       </span>
      //       <span style="font-weight: bold;">${volumeItem.value} 件</span>
      //     </div>`
      //   }
        
      //   return html
      // }
    },
    legend: {
      data: ['价格', '交易量'],
      top: 15,
      itemGap: 30,  // 增加图例间距
      textStyle: {
        fontSize: 14  // 增大图例字体
      }
    },
    grid: {
      left: '5%',  // 增加左侧间距
      right: '8%',  // 增加右侧间距
      bottom: '12%',
      top: '22%',  // 增加顶部间距，为标题留出空间
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: true,  // 改为true，使柱状图居中对齐
        data: dates,
        axisLine: {
          lineStyle: {
            color: '#ddd'
          }
        },
        axisTick: {
          alignWithLabel: true
        },
        axisLabel: {
          fontSize: 12,
          margin: 12  // 增加轴标签间距
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '价格',
        position: 'left',
        nameTextStyle: {
          padding: [0, 0, 0, 15],  // 调整名称位置
          fontSize: 13  // 增大轴名称字体
        },
        // axisLabel: {
        //   formatter: '{value} XIN豆',
        //   fontSize: 12,
        //   margin: 15  // 增加轴标签与轴线距离
        // },
        splitLine: {
          lineStyle: {
            color: '#f0f0f0',
            type: 'dashed'  // 使用虚线网格
          }
        },
        min: (value) => {
          return Math.floor(value.min * 0.9)
        }
      },
      {
        type: 'value',
        name: '交易量',
        position: 'right',
        nameTextStyle: {
          padding: [0, 15, 0, 0],  // 调整名称位置
          fontSize: 13  // 增大轴名称字体
        },
        // axisLabel: {
        //   formatter: '{value} 件',
        //   fontSize: 12,
        //   margin: 15  // 增加轴标签与轴线距离
        // },
        splitLine: {
          show: false  // 隐藏右侧坐标轴的网格线
        }
      }
    ],
    series: [
      {
        name: '价格',
        type: 'line',
        smooth: true,
        symbol: 'circle',  // 指定数据点形状
        symbolSize: 8,  // 增大数据点大小
        data: prices,
        lineStyle: {
          width: 4  // 增粗线条
        },
        itemStyle: {
          color: '#3a7bd5',
          borderWidth: 2,
          borderColor: '#fff'  // 添加白色边框突出显示
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(58, 123, 213, 0.3)'
            },
            {
              offset: 1,
              color: 'rgba(58, 123, 213, 0.05)'
            }
          ])
        }
      },
      {
        name: '交易量',
        type: 'bar',
        yAxisIndex: 1,
        barWidth: '40%',  // 调整柱状图宽度
        data: volumes,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#91cc75' },
            { offset: 1, color: '#5bae23' }
          ]),
          borderRadius: [4, 4, 0, 0]  // 圆角柱状图
        }
      }
    ]
  }
  
  // 设置图表选项
  priceChart.setOption(option)
}

onUnmounted(() => {
  if (priceChart) {
    priceChart.dispose()
  }
})


// 定义一个强制修复下拉框的函数 - 使用更激进的方式

// 应用下拉菜单修复的具体实现


// 组件挂载时获取数据
onMounted(async () => {
  globalLoading.value = true
  
  // 检测是否为CEF环境，如果是，添加特殊的CSS类
  try {
    await fetchUserBalance()
    await handleSearch()
    
    // 添加标签页切换监听
    watch(activeTab, handleTabChange)
    
    // 初始检查当前标签
    handleTabChange()
    
    // 添加点击外部关闭下拉框的事件监听
    document.addEventListener('click', handleClickOutside)
  } finally {
    globalLoading.value = false
  }
})

// 组件卸载时移除事件监听器
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

// 添加标签页状态
const activeTab = ref('myBag')

// 我的上架物品列表
const myListedItems = ref([])


// 上架对话框相关
const listItemDialogVisible = ref(false)
const listItemLoading = ref(false)
const inventoryItems = ref([]) // 存储背包中的所有物品
const selectedInventoryItem = ref(null) // 当前选中的物品
const inventoryTypeFilter = ref('all') // 背包物品类型筛选

// 背包搜索相关
const selectedInventorySearchItem = ref(null)
const inventoryItemSearchResults = ref([])
const inventoryItemSearchLoading = ref(false)
const hasInventorySearched = ref(false)
const isInventoryUserTyping = ref(false)
const inventorySearchInput = ref('')
const showInventorySearchResults = ref(false)
const isComposing = ref(false) // 中文输入法状态
const inventorySearchInputRef = ref(null) // 搜索输入框引用

// 背包分页相关
const inventoryCurrentPage = ref(1)
const inventoryPageSize = ref(10)
const inventoryTotal = ref(0)
const inventoryHasMore = ref(true)
const inventoryScrollLoading = ref(false)


// 获取标签类型
const getTagType = (type) => {
  switch(type) {
    case 'pet': return 'warning'
    case 'item': return 'success'
    case 'fashion': return 'info'
    default: return 'info'
  }
}

// 获取类型标签文本
const getTypeLabel = (type) => {
  const itemTypeLabels = {
    'pet': '精灵',
    'item': '道具',
    'fashion': '时装' 
  }
  return itemTypeLabels[type] || '未知'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

// 移动端背包可见性控制
const mobileBagVisible = ref(false)

// 修改打开背包对话框的方法，根据设备类型选择不同组件
const openListItemDialog = async () => {
  if (isMobile.value) {
    // 移动端：打开移动端背包
    mobileBagVisible.value = true
  } else {
    // PC端：保持原有逻辑
    resetListingForm()
    inventoryTypeFilter.value = 'all' // 重置类型筛选
    listItemDialogVisible.value = true
    await loadInventoryItems()
    // 确保滚动监听器在DOM渲染完成后添加
    nextTick(() => {
      addInventoryScrollListener()
    })
  }
}

// 添加一个对话框加载状态变量
const dialogLoading = ref(false)

// 加载背包物品
const loadInventoryItems = async (isLoadMore = false, itemType = null, itemId = null) => {
  if (isLoadMore) {
    inventoryScrollLoading.value = true
  } else {
    dialogLoading.value = true
    inventoryCurrentPage.value = 1
    inventoryItems.value = []
  }
  
  try {
    const params = {
      currentPage: inventoryCurrentPage.value,
      limit: inventoryPageSize.value
    }
    
    // 添加可选的itemType和itemId参数
    if (itemType !== null && itemType !== undefined) {
      params.itemType = itemType
    }
    if (itemId !== null && itemId !== undefined) {
      params.itemId = itemId
    }
    
    const response = await getUserItems(params)
    
    if (response.code === 200) {
      const newItems = response.data.map(item => {
        if (item.itemType === 1) {
          // 精灵类型
          let petData = {
            level: item.level || 0,
            dv: item.dv || 0,
            Nature: item.Nature,
            special: item.special,
            EVHP: item.EVHP || 0,
            EVAttack: item.EVAttack || 0,
            EVDefence: item.EVDefence || 0,
            EVSA: item.EVSA || 0,
            EVSD: item.EVSD || 0,
            EVSP: item.EVSP || 0,
            Shiny: item.Shiny,
            addMaxHP: item.addMaxHP || 0,
            catchTime: item.catchTime || 0
          };
          
          return {
            id: item.itemId,
            name: findItemNameById(item.itemId,item.itemType),
            type: convertItemType(item.itemType),
            image: getItemImage(item),
            description: '', // 接口未返回描述
            maxQuantity: 1, // 精灵只有1个
            level: petData.level || 0,
            iv: petData.dv || 0, // 个体值
            nature: getNatureName(petData.Nature), // 性格
            ability: getSpecialAbility(petData.special), // 特性
            isShiny: petData.Shiny === 1, // 是否为闪光精灵
            evHp: petData.EVHP || 0,
            evAtk: petData.EVAttack || 0,
            evDef: petData.EVDefence || 0,
            evSa: petData.EVSA || 0,
            evSd: petData.EVSD || 0,
            evSp: petData.EVSP || 0,
            addMaxHP: petData.addMaxHP || 0,
            catchTime: petData.catchTime || 0,
            uuid: item.uuid || 0
          }
        } else {
          // 道具类型
          return {
            id: item.itemId,
            name: findItemNameById(item.itemId,item.itemType),
            type: convertItemType(item.itemType),
            image: getItemImage(item),
            description: '', // 接口未返回描述
            maxQuantity: item.itemNum || 0,
            catchTime: item.catchTime || 0
          }
        }
      })
      
      // 处理分页数据
      if (isLoadMore) {
        inventoryItems.value = [...inventoryItems.value, ...newItems]
      } else {
        inventoryItems.value = newItems
      }
      
      // 更新分页信息
      inventoryTotal.value = response.total || newItems.length
      inventoryHasMore.value = newItems.length === inventoryPageSize.value
      
      // 默认选中第一个物品（仅在首次加载时）
      if (!isLoadMore && inventoryItems.value.length > 0) {
        selectInventoryItem(inventoryItems.value[0])
      }
    } else {
      ElMessage.error(response.msg || '加载背包物品失败')
    }
  } catch (error) {
    console.error('加载背包物品失败:', error)
    ElMessage.error('加载背包物品失败')
  } finally {
    if (isLoadMore) {
      inventoryScrollLoading.value = false
    } else {
      dialogLoading.value = false
    }
  }
}

// 加载更多背包物品
const loadMoreInventoryItems = async () => {
  if (inventoryScrollLoading.value || !inventoryHasMore.value) {
    return
  }
  
  try {
    inventoryCurrentPage.value++
    const itemType = inventoryTypeFilter.value === 'all' ? null : parseInt(inventoryTypeFilter.value)
    // 保持搜索状态：如果有搜索的物品ID，在滚动分页时也要传递
    const itemId = selectedInventorySearchItem.value || null
    await loadInventoryItems(true, itemType, itemId)
  } catch (error) {
    console.error('加载更多失败:', error)
    // 回滚页码
    inventoryCurrentPage.value--
    ElMessage.error('加载更多失败，请重试')
  }
}

// 创建inventory-list的ref引用
const inventoryListRef = ref(null)

// 滚动监听处理函数
let scrollTimeout = null
const handleInventoryScroll = (event) => {
  // 防抖处理
  if (scrollTimeout) {
    clearTimeout(scrollTimeout)
  }
  
  scrollTimeout = setTimeout(() => {
    const { scrollTop, scrollHeight, clientHeight } = event.target
    const distanceFromBottom = scrollHeight - scrollTop - clientHeight
    
    // 当滚动到距离底部50px时触发加载
    if (distanceFromBottom < 50 && inventoryHasMore.value && !inventoryScrollLoading.value) {
      loadMoreInventoryItems()
    }
  }, 100) // 100ms防抖
}

// 添加滚动监听
const addInventoryScrollListener = () => {
  nextTick(() => {
    if (inventoryListRef.value) {
      inventoryListRef.value.addEventListener('scroll', handleInventoryScroll, { passive: true })
    } else {
      setTimeout(() => {
        if (inventoryListRef.value) {
          inventoryListRef.value.addEventListener('scroll', handleInventoryScroll, { passive: true })
        }
      }, 100)
    }
  })
}

// 移除滚动监听
const removeInventoryScrollListener = () => {
  if (inventoryListRef.value) {
    inventoryListRef.value.removeEventListener('scroll', handleInventoryScroll)
  }
}

// 处理对话框关闭事件
const handleListItemDialogClose = () => {
  // 移除滚动监听
  removeInventoryScrollListener()
  // 调用原来的搜索刷新
  handleSearch()
}

// 确认上架商品
const confirmListItem = async () => {
  // 先显示确认对话框
  try {
    // 获取选中的物品名称
    const itemName = selectedInventoryItem.value.name;
    const price = listItemForm.value.price;
    const quantity = listItemForm.value.quantity;
    if (price < 15) {
      ElMessage.error(`价格不能低于15${CURRENCY.XIN_BEAN}`)
      return
    }
    if (price > 20000000) {
      ElMessage.error(`价格不能高于20000000${CURRENCY.XIN_BEAN}`)
      return
    }
    // 计算总价
    const totalPrice = price * quantity;
    
    // 显示确认对话框
    await ElMessageBox.confirm(
      `<div >
        <p><strong>商品:</strong> ${itemName}</p>
        <p><strong>单价:</strong> ${price} </p>
        <p><strong>数量:</strong> ${quantity}</p>
        <p style="color: #f56c6c; font-weight: bold; margin-top: 10px;">
          总价: ${formatPrice(totalPrice)}
        </p>
        <p style="color: #909399; font-size: 12px; margin-top: 15px;">
          成交后将收取15%手续费
        </p>
        <p style="color: #909399; font-size: 12px;">
          上架3分钟后才会出现在交易市场
        </p>
      </div>`,
      '上架确认',
      {
        confirmButtonText: '确认上架',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        type: 'info',
        center: true
      }
    );
    
    // 直接调用上架API
    const sellData = {
      itemId: selectedInventoryItem.value.id,
      itemType: getItemTypeCode(selectedInventoryItem.value.type),
      sellNum: listItemForm.value.quantity,
      unitPrice: listItemForm.value.price,
      catchTime: selectedInventoryItem.value.catchTime
    };
    
    await executeSell(sellData);
    
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消上架操作
      return;
    }
    console.error('上架物品失败:', error);
    ElMessage.error('上架物品失败，请重试');
  }
}

// 确认下架物品
const confirmRemoveItem = (item) => {

  ElMessageBox.confirm(
    `确定要下架物品 "${item.name}" 吗？`,
    '下架确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  .then(async () => {
    dialogLoading.value = true
    try {
      const response = await removeListingItem({
        listingId: item.listId,
        itemId: item.id,
        removeNum: item.quantity || 1,
        itemType: item.type === 'pet' ? 1 : 2,
        catchTime: item.catchTime
      })
      
      if (response.code === 200) {
        ElMessage.success('物品下架成功')
        // 刷新列表
        await loadMyListedItems()
        
        await loadInventoryItems()

      } else {
        ElMessage.error(response.msg || '下架物品失败')
      }
    } catch (error) {
      console.error('下架物品失败:', error)
      ElMessage.error('下架物品失败')
    } finally {
      dialogLoading.value = false
    }
  })
  .catch(() => {
    // 取消操作，不做任何处理
  })
}

// 加载我的上架物品
const loadMyListedItems = async () => {
  dialogLoading.value = true
  
  try {
    const response = await getMyListingItems()
    
    if (response.code === 200) {
      
      // 转换接口返回的数据为前端需要的格式
      myListedItems.value = response.data.map(item => {
        let catchTime = 0;
        let itemDesc = null;
        
        // 兼容CEF浏览器处理JSON解析
        if (item.itemType === 1) {
          try {
            let parsedDesc;
            // 尝试解析JSON
            if (typeof item.itemDesc === 'string') {
              parsedDesc = JSON.parse(item.itemDesc);
              catchTime = parsedDesc.catchTime || 0;
            } else if (typeof item.itemDesc === 'object') {
              parsedDesc = item.itemDesc;
              catchTime = parsedDesc.catchTime || 0;
            }
            itemDesc = formatPetAttributesToChinese(parsedDesc);
          } catch (error) {
            console.error('解析我的上架物品JSON失败:', error);
            itemDesc = "精灵数据无法读取";
          }
        }
        
        return {
          listId: item.listingId || item.itemId, // 优先使用listingId作为唯一标识
          id: item.itemId,
          orderId: item.orderId, // 新增orderId字段
          name: findItemNameById(item.itemId,item.itemType),
          type: convertItemType(item.itemType),
          price: item.unitPrice,
          quantity: item.quantity,
          listTime: item.listTime,
          catchTime: catchTime,
          image: getItemImage(item),
          itemDesc: itemDesc
        };
      })
    } else {
      ElMessage.error(response.msg || '获取我的上架物品失败')
    }
  } catch (error) {
    console.error('获取我的上架物品列表失败:', error)
    ElMessage.error('获取我的上架物品列表失败')
  } finally {
    dialogLoading.value = false
  }
}

// 监听标签变化
const handleTabChange = () => {
  if (activeTab.value === 'myBag' && listItemDialogVisible.value == true) {
    // 切换到我的背包标签时，加载我的背包物品
    loadInventoryItems()
  } else if (activeTab.value === 'myTrade' && listItemDialogVisible.value == true) {
    // 切换到我的交易标签时，加载我的上架物品
    loadMyListedItems()
  } else if (activeTab.value === 'tradeRecord' && listItemDialogVisible.value == true) {
    // 切换到交易记录标签时，加载交易历史
    loadTradeRecords()
  }
}


// 交易记录分页
const historyPage = ref(1)

// 日期时间格式化函数
const formatDateTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hour = String(d.getHours()).padStart(2, '0')
  const minute = String(d.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}


// 保留一个合并后的getStockCount函数，移除另一个重复的函数
const stockCounts = ref({}) // 存储每个商品ID对应的库存数量

// 合并两个函数的功能
const getStockCount = (item) => {
  // 优先使用API返回的quantity值
  if (item.quantity !== undefined) {
    return item.quantity
  }
  
  // 如果没有API数据，则使用或生成随机库存数量
  if (!stockCounts.value[item.id]) {
    // 如果没有为这个商品生成过库存数量，则随机生成一个(1-5)
    stockCounts.value[item.id] = Math.floor(Math.random() * 5) + 1
  }
  return stockCounts.value[item.id]
}

// 交易说明可见性
const noticeVisible = ref(isMobile.value ? false : true)


// 商品详情对话框相关
const currentDetailItem = ref(null)

// 打开商品详情 - 改进悬浮位置计算（优先显示右侧）
const openItemDetail = (item, event) => {
  // 防止点击按钮时触发详情打开
  if (event && event.target && (
    event.target.classList.contains('buy-button') ||
    event.target.closest('.buy-button')
  )) {
    return
  }
  
  // 设置当前展示的商品
  currentDetailItem.value = item
  
  // 获取触发元素（商品卡片）的位置和尺寸
  const cardElement = event.currentTarget
  const cardRect = cardElement.getBoundingClientRect()
  
  // 计算详情卡片应该显示的位置
  const detailCardWidth = 350 // 详情卡片宽度
  const windowWidth = window.innerWidth
  const windowHeight = window.innerHeight
  
  // 根据物品类型动态设置卡片高度
  const detailCardHeight = item.type === 'pet' ? 700 : 550
  
  // 确定悬浮卡片的最佳位置
  let xPosition, yPosition
  let positionType = ''
  
  // 第一步：检查是否可以在右侧显示（优先选择）
  if (windowWidth - cardRect.right >= detailCardWidth + 10) {
    // 右侧有足够空间
    xPosition = cardRect.right + 10
    yPosition = Math.min(
      Math.max(10, cardRect.top),
      windowHeight - detailCardHeight - 10
    )
    positionType = 'right'
  } 
  // 第二步：检查是否可以在左侧显示
  else if (cardRect.left >= detailCardWidth + 10) {
    // 左侧有足够空间
    xPosition = cardRect.left - detailCardWidth - 10
    yPosition = Math.min(
      Math.max(10, cardRect.top),
      windowHeight - detailCardHeight - 10
    )
    positionType = 'left'
  }
  // 第三步：检查是否可以在上方显示
  else if (cardRect.top >= detailCardHeight + 10) {
    // 上方有足够空间
    xPosition = Math.min(
      Math.max(10, cardRect.left),
      windowWidth - detailCardWidth - 10
    )
    yPosition = cardRect.top - detailCardHeight - 10
    positionType = 'top'
  }
  // 第四步：检查是否可以在下方显示
  else if (windowHeight - cardRect.bottom >= detailCardHeight + 10) {
    // 下方有足够空间
    xPosition = Math.min(
      Math.max(10, cardRect.left),
      windowWidth - detailCardWidth - 10
    )
    yPosition = cardRect.bottom + 10
    positionType = 'bottom'
  }
  // 最后：如果都不满足，选择最大的可用空间
  else {
    // 计算四个方向的可用空间
    const spaceLeft = cardRect.left
    const spaceRight = windowWidth - cardRect.right
    const spaceTop = cardRect.top
    const spaceBottom = windowHeight - cardRect.bottom
    
    // 找出最大的可用空间
    const maxSpace = Math.max(spaceLeft, spaceRight, spaceTop, spaceBottom)
    
    if (maxSpace === spaceRight) {
      // 右侧空间最大
      xPosition = Math.min(cardRect.right + 10, windowWidth - detailCardWidth - 10)
      yPosition = Math.max(10, Math.min(cardRect.top, windowHeight - detailCardHeight - 10))
      positionType = 'right'
    } else if (maxSpace === spaceLeft) {
      // 左侧空间最大
      xPosition = Math.max(10, cardRect.left - detailCardWidth - 10)
      yPosition = Math.max(10, Math.min(cardRect.top, windowHeight - detailCardHeight - 10))
      positionType = 'left'
    } else if (maxSpace === spaceTop) {
      // 上方空间最大
      xPosition = Math.max(10, Math.min(cardRect.left, windowWidth - detailCardWidth - 10))
      yPosition = Math.max(10, cardRect.top - detailCardHeight - 10)
      positionType = 'top'
    } else {
      // 下方空间最大
      xPosition = Math.max(10, Math.min(cardRect.left, windowWidth - detailCardWidth - 10))
      yPosition = Math.min(cardRect.bottom + 10, windowHeight - detailCardHeight - 10)
      positionType = 'bottom'
    }
  }
  
  // 确保卡片不会超出视口边界
  xPosition = Math.max(10, Math.min(xPosition, windowWidth - detailCardWidth - 10))
  yPosition = Math.max(10, Math.min(yPosition, windowHeight - detailCardHeight - 10))
  
  // 设置详情卡片位置
  detailCardPosition.value = {
    x: xPosition,
    y: yPosition
  }
  
  // 使用nextTick确保DOM已经更新
  nextTick(() => {
    // 根据物品类型和显示位置设置自定义类名
    const detailCardElement = document.querySelector('.item-detail-card')
    if (detailCardElement) {
      detailCardElement.classList.remove('pet-type', 'item-type', 'top-position', 'right-position', 'bottom-position', 'left-position')
      detailCardElement.classList.add(
        item.type === 'pet' ? 'pet-type' : 'item-type',
        `${positionType}-position`
      )
    }
    
    // 直接使用物品自带的价格历史数据初始化图表
    initDetailPriceChart(item)
  })
}

// 在script中添加全局加载状态变量
const globalLoading = ref(false)


// 上架表单
const listItemForm = ref({
  price: 0,
  quantity: 1
})

// 重置上架表单
const resetListingForm = () => {
  selectedInventoryItem.value = null
  listItemForm.value = {
    price: 0,
    quantity: 1
  }
}

// 添加防抖函数
const debounce = (fn, delay) => {
  let timer = null
  return function(...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 处理背包搜索输入变化
const handleInventoryInputChange = (event) => {
  const val = event.target ? event.target.value : event
  inventorySearchInput.value = val
  
  // 如果正在使用中文输入法，不触发搜索
  if (isComposing.value) {
    return
  }
  
  if (!val) {
    showInventorySearchResults.value = false
    inventoryItemSearchResults.value = []
    hasInventorySearched.value = false
    isInventoryUserTyping.value = false
    inventoryItemSearchLoading.value = false
    return
  }
  
  showInventorySearchResults.value = true
  isInventoryUserTyping.value = true
  searchItemsForInventory(val)
}

// 中文输入法开始
const handleCompositionStart = () => {
  isComposing.value = true
}

// 中文输入法结束
const handleCompositionEnd = (event) => {
  isComposing.value = false
  // 输入法结束后，手动触发一次搜索
  handleInventoryInputChange(event)
}

// 输入框获得焦点
const handleInputFocus = () => {
  // 如果有输入内容，显示搜索结果
  if (inventorySearchInput.value) {
    showInventorySearchResults.value = true
  }
}

// 清除搜索输入
const clearInventorySearch = () => {
  inventorySearchInput.value = ''
  showInventorySearchResults.value = false
  inventoryItemSearchResults.value = []
  hasInventorySearched.value = false
  isInventoryUserTyping.value = false
  inventoryItemSearchLoading.value = false
  selectedInventorySearchItem.value = null
  
  // 清除搜索后重新加载完整的背包物品列表
  const itemType = inventoryTypeFilter.value === 'all' ? null : parseInt(inventoryTypeFilter.value)
  loadInventoryItems(false, itemType, null)
}

// 搜索背包物品 - 使用防抖
const searchItemsForInventory = debounce((query) => {
  if (!query) {
    inventoryItemSearchResults.value = []
    hasInventorySearched.value = false
    inventoryItemSearchLoading.value = false
    isInventoryUserTyping.value = false
    showInventorySearchResults.value = false
    return
  }
  
  inventoryItemSearchLoading.value = true
  // 执行实际搜索
  searchInventoryItems(query)
}, 300)

// 选择搜索结果项
const selectInventorySearchItem = async (item) => {
  selectedInventorySearchItem.value = item.id
  inventorySearchInput.value = `${item.name} (ID: ${item.id})`
  showInventorySearchResults.value = false
  
  try {
    // 调用loadInventoryItems函数，传入itemId参数来筛选特定物品
    await loadInventoryItems(false, null, item.id)
    console.log('成功加载物品ID为', item.id, '的背包物品')
    ElMessage.success('成功加载相关物品')
  } catch (error) {
    console.error('获取物品详情失败:', error)
    ElMessage.error('获取物品详情失败')
  }
}

// 点击外部关闭下拉框
const handleClickOutside = (event) => {
  const searchSection = event.target.closest('.inventory-search-section')
  
  // 如果点击在搜索区域外，且输入框没有焦点，才关闭下拉框
  if (!searchSection && document.activeElement !== inventorySearchInputRef.value) {
    showInventorySearchResults.value = false
  }
}

// 搜索物品
const searchInventoryItems = async (query) => {
  if (!query) {
    inventoryItemSearchResults.value = []
    hasInventorySearched.value = false
    isInventoryUserTyping.value = false
    return
  }

  try {
    // 使用本地 itemFinder 工具进行搜索
    const results = findItemsByKeyword(query)
    
    // 限制搜索结果数量，避免显示过多结果
    const limitedResults = results.slice(0, 20)
    
    inventoryItemSearchResults.value = limitedResults
  } catch (error) {
    console.error('搜索物品失败:', error)
    inventoryItemSearchResults.value = []
    ElMessage.error('搜索物品失败')
  } finally {
    // 设置搜索已完成标志
    hasInventorySearched.value = true
    isInventoryUserTyping.value = false
    
    // 延迟关闭加载状态
    setTimeout(() => {
      inventoryItemSearchLoading.value = false
      // 确保输入框保持焦点
      nextTick(() => {
        if (inventorySearchInputRef.value && document.activeElement !== inventorySearchInputRef.value) {
          inventorySearchInputRef.value.focus()
        }
      })
    }, 200)
  }
}

// 处理背包类型筛选变化
const handleInventoryTypeChange = () => {
  const itemType = inventoryTypeFilter.value === 'all' ? null : parseInt(inventoryTypeFilter.value)
  // 保持搜索状态：如果有搜索的物品ID，在切换类型时也要传递
  const itemId = selectedInventorySearchItem.value || null
  loadInventoryItems(false, itemType, itemId)
}

// 选择背包物品
const selectInventoryItem = (item) => {
  selectedInventoryItem.value = item
  listItemForm.value.quantity = 1
}

// 计算预期收入
const calculateExpectedIncome = () => {
  if (!listItemForm.value.price) return 0
  
  const totalPrice = listItemForm.value.price * (listItemForm.value.quantity || 1)
  const fee = Math.max(1, totalPrice * 0.05) // 15%手续费，最低1
  return Math.round(totalPrice - fee)
}

// 是否可以设置数量
const canSetQuantity = computed(() => {
  return selectedInventoryItem.value && 
         selectedInventoryItem.value.type === 'item' && 
         selectedInventoryItem.value.maxQuantity > 1
})

// 是否可以提交上架
const canSubmitListing = computed(() => {
  return selectedInventoryItem.value && 
         listItemForm.value.price > 15 &&
         listItemForm.value.quantity > 0
})

// 获取个体值的CSS类名
const getIvClass = (iv) => {
  if (!iv) return 'iv-common';
  
  const ivNum = parseInt(iv);
  if (ivNum >= 10) return 'iv-perfect';
  if (ivNum >= 20) return 'iv-great';
  if (ivNum >= 30) return 'iv-good';
  return 'iv-common';
}

// 校验上架数量
const validateQuantity = (value) => {
  // 如果输入的数量大于最大可用数量，则重置为最大数量
  if (value > (selectedInventoryItem.value?.maxQuantity || 1)) {
    listItemForm.value.quantity = selectedInventoryItem.value?.maxQuantity || 1
    
    // 弹出提示
    ElMessage.warning(`上架数量不能超过当前拥有的数量：${selectedInventoryItem.value?.maxQuantity || 1}`)
  }
}

// const currentDetailItem = ref(null)
const detailCardPosition = ref({ x: 0, y: 0 })



// 添加初始化详情卡片中价格走势图的方法
const detailChartInstance = ref(null)
const detailChartContainer = ref(null) // 添加这一行，引用图表容器

const initDetailPriceChart = (item) => {
  if (!detailChartContainer.value) return
  
  // 如果已有图表实例，先销毁
  if (detailChartInstance.value) {
    detailChartInstance.value.dispose()
  }
  
  // 创建新的图表实例
  const chart = echarts.init(detailChartContainer.value)
  detailChartInstance.value = chart
  
  // 准备图表数据
  const dates = [];
  const prices = [];
  
  // 检查是否有真实的价格历史数据
  const hasPriceHistory = item.priceHistory && 
                         Array.isArray(item.priceHistory) && 
                         item.priceHistory.length > 0 &&
                         item.priceHistory.some(record => record.price !== undefined);
  
  if (hasPriceHistory) {
    // 只使用有效的价格数据
    item.priceHistory.forEach(record => {
      if (record.date && record.price !== undefined && record.price !== null) {
        const dateObj = new Date(record.date);
        const month = dateObj.getMonth() + 1;
        const day = dateObj.getDate();
        dates.push(`${month}/${day}`);
        prices.push(record.price);
      }
    });
  }
  
  // 如果没有有效价格数据，则显示提示信息
  if (prices.length === 0) {
    chart.setOption({
      title: {
        text: '暂无历史价格数据',
        left: 'center',
        top: 'middle',
        textStyle: {
          color: '#909399',
          fontSize: 14,
          fontWeight: 'normal'
        }
      },
      grid: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0
      },
      xAxis: { show: false },
      yAxis: { show: false },
      series: []
    });
    return;
  }
  
  // 有正常数据时的图表配置
  const option = {
    grid: {
      top:25,
      right: 20,
      bottom: 20,
      left: 5,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        fontSize: 10,
        interval: 0,
        rotate: 0
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 10,
        formatter: (value) => {
          if (value >= 10000) {
            return (value / 10000).toFixed(1) + 'w';
          }
          return value % 1 === 0 ? value : value.toFixed(1);
        }
      },
      min: function(value) {
        return Math.max(0, Math.floor(value.min * 0.8));
      }
    },
    series: [{
      data: prices,
      type: 'line',
      smooth: true,
      lineStyle: {
        width: 2,
        color: '#409EFF'
      },
      label: {
        show: true,
        position: 'top',
        formatter: (params) => {
          if (params.value >= 10000) {
            return (params.value / 10000).toFixed(1) + 'w';
          }
          return params.value;
        },
        fontSize: 12,
        color: '#606266',
        backgroundColor: 'rgba(255, 255, 255, 0.8)',
        padding: [2, 4],
        borderRadius: 2
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(64, 158, 255, 0.25)'
          }, {
            offset: 1, color: 'rgba(64, 158, 255, 0.05)'
          }]
        }
      }
    }]
  };
  
  // 设置图表配置
  chart.setOption(option);
  
  // 延迟一点时间后刷新图表大小，确保正确渲染
  setTimeout(() => {
    chart.resize();
  }, 100);
}

// 修改鼠标离开处理，清理图表资源
const hideItemDetail = () => {
  if (detailChartInstance.value) {
    detailChartInstance.value.dispose()
    detailChartInstance.value = null
  }
  currentDetailItem.value = null
}

// 在适当位置添加以下变量
const buyQuantityDialogVisible = ref(false)
const currentBuyItem = ref(null)
const buyQuantity = ref(1)

// 添加确认购买方法
const confirmBuy = async () => {
  if (!currentBuyItem.value) return
  
  try {
    // 准备购买数据
    const buyData = { 
      listingId: currentBuyItem.value.listId, // 使用存储的listingId
      buyNum: buyQuantity.value, // 购买数量
      catchTime: currentBuyItem.value.type === 'pet' ? 0 : (currentBuyItem.value.catchTime || 0) // 获取时间，精灵则为0
    };
    
    // 调用统一的购买方法
    await executeBuy(buyData);
  } catch (error) {
    console.error('购买失败:', error)
    ElMessage.error('购买失败')
  }
}

// 计算总价方法
const calculateTotalPrice = () => {
  if (!currentBuyItem.value) return 0
  return (currentBuyItem.value.price * buyQuantity.value).toFixed(2)
}


// 为没有描述的道具提供默认描述
const getDefaultItemDescription = (itemName) => {
  
  const defaultDescriptions = {
    '能量药剂': '提供宠物战斗所需的能量，可以恢复战斗中的宠物。',
    '经验宝珠': '能够为宠物提供额外的经验值，加速宠物升级。',
    '进化石': '特殊的能量石，能够帮助某些宠物进化为更强大的形态。',
    '学习装置': '可以帮助宠物学习特定的技能或提升学习力。',
    'XIN徽章': '象征荣誉的徽章，在XIN计划世界中具有特殊意义。',
    'XIN豆': 'XIN计划世界的通用货币，可用于购买各类物品。'
  }
  
  // 尝试从名称中匹配关键词
  for (const [key, desc] of Object.entries(defaultDescriptions)) {
    if (itemName.includes(key)) {
      return desc
    }
  }
  
  // 返回通用描述
  return '来自XIN计划世界的神秘道具，可能具有特殊效果。'
}

// 添加表格行class名，用于自定义悬停样式
const tableRowClassName = () => {
  return 'hoverable-row';
}

/**
 * 将精灵属性JSON转换为中文可读格式
 * @param {Object|string} petData - 精灵属性JSON或字符串
 * @return {string} 格式化的中文描述
 */
const formatPetAttributesToChinese = (petData) => {
  // 如果输入是字符串，尝试解析为JSON对象
  if (typeof petData === 'string') {
    try {
      petData = JSON.parse(petData);
    } catch (e) {
      console.error('解析JSON失败:', e);
      return '数据格式错误';
    }
  }
  
  // 如果petData不是对象或为null，返回错误信息
  if (!petData || typeof petData !== 'object') {
    return '无效数据';
  }
  
  // 属性映射表
  const attributeMap = {
    'level': '等级',
    'iv': '个体',
    'nature': '性格',
    'ability': '特性',
    'evHp': 'HP',
    'evAtk': '攻击',
    'evDef': '防御',
    'evSa': '特攻',
    'evSd': '特防',
    'evSp': '速度',
    'addMaxHP': '额HP',
    'isShiny': '异色',
    // 'catchTime': '捕获时间'
  };
  
  // 组装描述文本
  let description = '';
  
  // 首先添加关键属性
  const keyProperties = ['level', 'iv', 'nature', 'ability'];
  keyProperties.forEach(key => {
    if (petData[key] !== undefined) {
      description += `${attributeMap[key]}: ${key === 'isShiny' ? (petData[key] ? '是' : '否') : petData[key]}\t`;
    }
  });
  
  // 添加学习力属性
  if (Object.keys(petData).some(key => key.startsWith('ev'))) {
    description += '\t学习力:\t';
    ['evHp', 'evAtk', 'evDef', 'evSa', 'evSd', 'evSp'].forEach(key => {
      if (petData[key] !== undefined) {
        description += `${attributeMap[key].replace('学习力', '')}: ${petData[key]} `;
      }
    });
    description = description.trim() + '\t';
  }
  
  // 添加其他属性
  if (petData.addMaxHP) {
    description += `\n${attributeMap.addMaxHP}: ${petData.addMaxHP}\t`;
  }
  
  if (petData.isShiny !== undefined) {
    description += `${attributeMap.isShiny}: ${petData.isShiny ? '是' : '否'}\t\t`;
  }
  
  return description;
}

// 判断物品是否被选中 - 精灵用ID和捕获时间组合判断，道具仅用ID
const isItemSelected = (item) => {
  if (!selectedInventoryItem.value) return false;
  
  if (item.type === 'pet') {
    // 精灵比较ID和捕获时间
    return selectedInventoryItem.value.id === item.id && 
           selectedInventoryItem.value.catchTime === item.catchTime;
  } else {
    // 道具只比较ID
    return selectedInventoryItem.value.id === item.id;
  }
}

// 交易记录相关数据和方法
const historyLoading = ref(false)
const tradeHistory = ref([])
const historyTotal = ref(0)
const historyCurrentPage = ref(1)
const historyPageSize = ref(10)

// 历史查询表单
const historyForm = reactive({
  type: '', // 'buy' 或 'sell'
  dateRange: []
})

// 加载交易记录
const loadTradeRecords = async () => {
  historyLoading.value = true
  
  try {
    // 确保使用正确的页码参数
    const params = {
      currentPage: historyPage.value,
      limit: historyPageSize.value
    }
    
    // 添加交易类型过滤
    if (historyForm.type) {
      // 转换为接口需要的数字格式
      params.tradeType = historyForm.type === 'buy' ? 1 : 2
    }
    
    // 添加时间范围过滤
    if (historyForm.dateRange && historyForm.dateRange.length === 2) {
      params.startTime = historyForm.dateRange[0] + ' 00:00:00'
      params.endTime = historyForm.dateRange[1] + ' 23:59:59'
    }
    
    const response = await getTradeRecords(params)
    
    if (response.code === 200 && response.data) {
      // 转换API返回数据为前端需要的格式
      tradeHistory.value = response.data.list.map(item => {
        let itemDesc = "这是一个神奇的XIN计划道具,具有神奇的效果";
        
        if (item.itemType === 1) {
          try {
            // 为CEF浏览器添加兼容性处理
            if (typeof item.itemDesc === 'string') {
              itemDesc = formatPetAttributesToChinese(item.itemDesc);
            } else if (typeof item.itemDesc === 'object') {
              itemDesc = formatPetAttributesToChinese(item.itemDesc);
            } else if (typeof item.itemDesc === 'undefined') {
              itemDesc = "数据已过期";
            }
          } catch (error) {
            console.error('解析交易记录物品描述失败:', error);
            itemDesc = "精灵数据无法读取";
          }
        }
        
        return {
          id: item.recordId,
          itemId: item.itemId,           // 新增: 物品ID
          itemName: findItemNameById(item.itemId,item.itemType),
          itemType: convertItemType(item.itemType),  // 转换为前端使用的类型格式
          time: item.create_time,
          type: item.tradeType === 1 ? 'buy' : 'sell',
          price: item.amount,
          orderId: item.orderId,        // 订单ID
          // 物品图片处理
          image: getItemImage(item),
          targetUser: item.account,       // 交易对象账号
          itemDesc: itemDesc
        }
      })
      
      historyTotal.value = response.data.totalCount
    } else {
      ElMessage.error(response.msg || '获取交易记录失败')
    }
  } catch (error) {
    console.error('加载交易记录失败:', error);
    ElMessage.error('加载交易记录失败');
  } finally {
    historyLoading.value = false;
  }
}

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(historyTotal.value / historyPageSize.value);
});


// 搜索历史记录
const searchHistory = () => {
  historyCurrentPage.value = 1
  loadTradeRecords()
}

// 重置历史搜索
const resetHistorySearch = () => {
  historyForm.type = ''
  historyForm.dateRange = []
  historyCurrentPage.value = 1
  loadTradeRecords()
}

// 处理历史分页变化 - 重新实现
const handleHistoryPageChange = (page) => {
  historyPage.value = page
  loadTradeRecords() // 重新加载交易记录
}

// 处理每页显示条目变化
const handleHistorySizeChange = (size) => {
  historyPageSize.value = size
  historyPage.value = 1 // 切换每页数量时重置为第一页
  loadTradeRecords()
}



// 初始化时加载交易记录
onMounted(() => {
  // 监听窗口大小变化，动态更新设备类型
  if (activeTab.value === 'tradeHistory') {
    loadTradeRecords()
  }
})

// 监听标签页切换，当切换到交易记录标签时加载数据
watch(activeTab, (newVal) => {
  if (newVal === 'tradeHistory') {
    loadTradeRecords()
  } else if (newVal === 'myBag') {
    // 当切换到我的背包时，确保滚动监听器正确添加
    nextTick(() => {
      addInventoryScrollListener()
    })
  }
})

// 添加用户余额状态
const userBalance = ref(0)
const tradeBalance = ref(0)

// 获取用户余额
const fetchUserBalance = async () => {
  try {
    const response = await getUserBalance()
    if (response.code === 200) {
      // userBalance.value = response.data.gameBalance
      tradeBalance.value = response.data.tradeBalance
    } else {
      console.error('获取余额失败:', response.msg)
    }
  } catch (error) {
    console.error('获取余额接口异常:', error)
  }
}


// 确保在script部分导出这个函数以便在模板中使用
const formatPriceDisplay = (price, showSymbol = false) => {
  return formatPrice(price, showSymbol)
}

// 处理购买操作
const handleBuy = async (item) => {
  
  // 如果是道具类型，打开数量选择对话框
  if (item.type === 'item' || item.type === 'prop' || item.type === 'fashion') {
    currentBuyItem.value = item;
    buyQuantity.value = 1;
    buyQuantityDialogVisible.value = true;
    return;
  }
  
  // --- 宠物购买确认 (精确模仿悬浮卡片 v3) ---
  if (item.type === 'pet') {
    try {
      const desc = item.description || {};
      const tagType = getTagType(item.type); // 确保 getTagType 在作用域内
      const tagLabel = getTypeLabel(item.type); // 确保 getTypeLabel 在作用域内
      const ivClass = getIvClass(desc.iv); // 确保 getIvClass 在作用域内

      // 构建与悬浮卡片 *完全一致* 的 HTML
      const confirmCardHTML = `
        <div class="item-detail-card" style="position: relative; box-shadow: none; border: none; padding: 16px; background: #fff;"> 
          <div class="detail-card-header">
            <div class="detail-card-image">
              <img src="${item.image || defaultAvatar}" alt="${item.name}" style="display: block; width:100%; height:100%; object-fit:contain; border-radius: 8px;"/>
              ${desc.isShiny ? '<span class="shiny-tag">异色</span>' : ''}
            </div>
            <div class="detail-card-title">
              <h3>${item.name}</h3>
              <span class="el-tag el-tag--small el-tag--${tagType}">${tagLabel}</span>
            </div>
          </div>

          <div class="detail-card-content">
            <div class="detail-info-row">
              <div class="detail-info-item">
                <span class="info-label">价格</span>
                <span class="info-value price">
                  <svg t="1744176905853" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6957" width="14" height="14" style="margin-right: 3px; fill: #ff5722;"><path d="M60.974268 623.892437A430.636588 430.636588 0 0 1 13.963573 508.087872c-7.074877-29.788956-15.35993-67.956055-13.684302-110.219135 2.513443-62.277535 8.005782-112.360217 40.401271-189.252958 79.685456-188.973686 246.689788-247.527602 395.634566-183.9468 148.758597 63.673892 87.132695 227.606238 279.271458 376.644106 53.061577 41.145995 52.130672 45.335067 89.087595 64.790978 36.863832 19.455912 73.541484 36.026018 101.282448 53.62012 54.364844 34.722751 83.036713 65.814974 100.723906 97.372648 11.822492 21.03845 12.567216 39.098004 15.080659 58.926278 1.86181 13.591211 2.606534 21.503902 2.234171 36.026018a272.196581 272.196581 0 0 1-6.981786 44.683433c-17.035559 57.43683-26.716969 74.75166-41.332176 98.024282-14.894478 24.389707-33.512575 46.265972-55.295748 64.604797-33.047123 29.416594-46.824514 40.30818-71.586584 51.292858-22.341717 10.053772-53.992482 20.479907-116.363108 38.818733-52.316853 15.35993-127.627056 17.128649-181.247176 11.822491-26.716969-2.606534-83.129804-19.828274-95.697019-25.134431-18.338826-7.72651-34.722751-14.056663-50.920496-22.248626a937.235013 937.235013 0 0 1-105.657702-65.721883c-40.587452-28.858051-87.411966-76.334198-109.102049-99.51373-18.990459-20.293726-31.650765-37.701647-45.614338-56.226653-20.479907-27.368603-42.635443-59.577911-83.129804-128.464871v-0.09309z m435.849656-338.477007a23.831164 23.831164 0 0 0-37.050014-11.636311 70.562588 70.562588 0 0 0-26.437698 68.88696c4.282162 21.969355 12.753397 41.332176 25.786065 57.995373 14.801387 19.17664 35.467475 34.908932 62.091354 47.196876 22.155536 10.239953 48.220872 6.888696 67.211331-8.564325a23.924255 23.924255 0 0 0-2.606534-38.818732 202.471807 202.471807 0 0 1-54.178663-48.407053 215.969927 215.969927 0 0 1-34.815841-66.652788z" p-id="6958"></path></svg>
                  <strong>${formatPriceDisplay(item.price)}</strong>
                </span>
              </div>
              <div class="detail-info-item">
                <span class="info-label">卖家</span>
                <span class="info-value seller">
                  <img src="https://robohash.org/10.png" class="seller-avatar" alt="seller" style="width: 20px; height: 20px; border-radius: 50%; vertical-align: middle; margin-right: 4px; flex-shrink: 0;"/> 
                  ${item.seller}
                </span>
              </div>
            </div>

            <div class="detail-pet-info">
              <div class="pet-info-row">
                <div class="pet-info-item">
                  <span class="info-label">等级</span>
                  <span class="info-value level">Lv.${desc.level || '?'}</span>
                </div>
                <div class="pet-info-item">
                  <span class="info-label">个体</span>
                  <span class="info-value iv ${ivClass}">${desc.iv || 0}</span>
                </div>
              </div>
              <div class="pet-stats">
                 <div class="stat-item"><span class="stat-label">性格</span><span class="stat-value">${desc.nature || '未知'}</span></div>
                 <div class="stat-item"><span class="stat-label">特性</span><span class="stat-value">${desc.ability || '无特性'}</span></div>
                 <div class="stat-item"><span class="stat-label">额HP</span><span class="stat-value">${desc.addMaxHP || 0}</span></div>
              </div>
              <div class="pet-stats" style="margin-top: 8px;">
                <div class="stat-item"><span class="stat-label">HP</span><span class="stat-value">${desc.evHp || 0}</span></div>
                <div class="stat-item"><span class="stat-label">攻击</span><span class="stat-value">${desc.evAtk || 0}</span></div>
                <div class="stat-item"><span class="stat-label">防御</span><span class="stat-value">${desc.evDef || 0}</span></div>
                <div class="stat-item"><span class="stat-label">特攻</span><span class="stat-value">${desc.evSa || 0}</span></div>
                <div class="stat-item"><span class="stat-label">特防</span><span class="stat-value">${desc.evSd || 0}</span></div>
                <div class="stat-item"><span class="stat-label">速度</span><span class="stat-value">${desc.evSp || 0}</span></div>
              </div>
            </div>
            <p class="confirm-action-text-v2">确定要购买这只精灵吗？</p> 
          </div>
        </div>
      `;

      // 调用 ElMessageBox.confirm
    await ElMessageBox.confirm(
        confirmCardHTML, 
        '购买确认', // 标题会被隐藏
      {
          confirmButtonText: '确认购买',
        cancelButtonText: '取消',
          customClass: 'pet-buy-messagebox-exact-match', // 确保 CSS 类名正确
          dangerouslyUseHTMLString: true,
          center: true, 
          showClose: false, 
          // 移除 type 以便 customClass 完全控制样式
        }
      );
      
      // 用户确认后的购买逻辑...
      const buyData = { 
      listingId: item.listId,
      itemId: item.id,
      itemName: item.name,
        itemType: 1, 
        buyNum: 1, 
        itemDesc: JSON.stringify(desc), 
      unitPrice: item.price,
      sellerAccount: item.seller,
        catchTime: desc?.catchTime || 0
      };
      await executeBuy(buyData);

  } catch (error) {
    if (error !== 'cancel') {
      console.error('购买失败:', error);
      ElMessage.error('购买失败');
    }
      // 用户取消，不处理
    }
    return; // 结束宠物处理
  }
  
  // 如果代码能执行到这里，说明类型未知或有误 (道具逻辑已移出)
  console.warn('未知的购买项目类型:', item.type);
  ElMessage.warning('无法购买此类型的物品');
};

// 确认道具数量购买
const confirmQuantityBuy = async () => {
  if (!currentBuyItem.value) return;
  
  try {
    // 计算总价
    const totalPrice = currentBuyItem.value.price * buyQuantity.value;
    
    // 直接调用购买API
    const buyData = {
      listingId: currentBuyItem.value.listId,
      itemId: currentBuyItem.value.id,
      itemName: currentBuyItem.value.name,
      itemType: currentBuyItem.value.type === 'pet' ? 1 : 2,
      buyNum: buyQuantity.value,
      unitPrice: currentBuyItem.value.price,
      sellerAccount: currentBuyItem.value.seller
    };
    
    // 关闭数量选择对话框
      buyQuantityDialogVisible.value = false;
    
    // 执行购买操作
    await executeBuy(buyData);
    
  } catch (error) {
    console.error('购买失败:', error);
    ElMessage.error('购买失败');
  }
};


const syncAccountLoading = ref(false)


// 同步交易行账户
const syncTradeAccount = async () => {
  syncAccountLoading.value = true
  try {
    // 同步账户余额 - 使用游戏内余额作为同步参数
    const response = await syncTradeBalance(tradeBalance.value)
    if (response.code === 200) {
      // 同步成功后刷新余额信息
      await fetchUserBalance()
      ElMessage.success('账户余额同步成功')
    } else {
      ElMessage.warning(response.msg || '同步余额失败')
    }
  } catch (error) {
    console.error('同步账户余额异常:', error)
    ElMessage.error('同步账户余额失败')
  } finally {
    syncAccountLoading.value = false
  }
}

// 在挂载时获取账户信息
// onMounted(() => {
//   // fetchTradeAccountInfo()
//   fetchUserBalance()
// })

// 判断是否为CEF浏览器
const isCEF = ref(isCEFBrowser());

// 二级密码相关
const secondaryPasswordVisible = ref(false);
const secondaryPasswordForm = reactive({
  password: ''
});
const secondaryPasswordFormRef = ref(null);
const verificationLoading = ref(false);
const pendingOperation = ref(null);

// 确认二级密码验证
const confirmSecondaryPassword = async () => {
  if (!pendingOperation.value) return;

  // 验证二级密码格式
  if (!/^\d{6}$/.test(secondaryPasswordForm.password)) { // 修复了正则表达式
    ElMessage.error('二级密码必须是6位数字');
    return;
  }

  verificationLoading.value = true;

  try {
    // 1. 校验二级密码
    const verifyResponse = await verifySecondaryPassword({
      password: secondaryPasswordForm.password
    });

    if (verifyResponse.code !== 200) {
      ElMessage.error(verifyResponse.msg || '二级密码错误，请重新输入');
      verificationLoading.value = false;
      return;
    }

    // 2. 密码验证成功提示
    ElMessage.success('二级密码验证成功，正在重新尝试操作...');
    secondaryPasswordVisible.value = false; // 关闭密码弹窗

    // 3. 重新执行之前的操作
    if (pendingOperation.value.type === 'buy') {
      executeBuy(pendingOperation.value.data, false).catch(err => {
        console.error('重新执行购买失败:', err);
      });
    } else if (pendingOperation.value.type === 'sell') {
      executeSell(pendingOperation.value.data, false).catch(err => {
        console.error('重新执行上架失败:', err);
      });
    }

    // 4. 重置表单状态
    secondaryPasswordForm.password = '';
    pendingOperation.value = null;

  } catch (error) {
    console.error('二级密码验证失败:', error);
    ElMessage.error('二级密码验证失败，请重试');
  } finally {
    verificationLoading.value = false;
  }
};

// 执行购买操作
const executeBuy = async (data, isFirstAttempt = true) => {
  globalLoading.value = true;
  loading.value = true;
  
  try {
    const response = await buyItem(data);
    
    if (response.code === 200) {
      // 购买成功
      ElMessage.success('购买成功！');
      if(isMobile){
        itemListRef.value?.closeDetailDialog();
      }
      // 刷新物品列表
      handleSearch();
      // 更新余额
      fetchUserBalance();
      
      // 重置任何可能存在的二级密码状态
      secondaryPasswordVisible.value = false;
      secondaryPasswordForm.password = '';
      pendingOperation.value = null;
    } else if (response.code === 9 && isFirstAttempt) {
      pendingOperation.value = {
        type: 'buy',
        data: data
      };
      secondaryPasswordVisible.value = true;
      ElMessage.warning('需要二级密码验证');
    } else {
      // 其他错误
      ElMessage.error(response.msg || '购买失败');
    }
  } catch (error) {
    console.error('购买失败:', error);
    ElMessage.error('购买失败');
  } finally {
    globalLoading.value = false;
    loading.value = false;
  }
};

// 执行上架操作
const executeSell = async (data, isFirstAttempt = true) => {
  listItemLoading.value = true;
  
  try {
    const response = await sellItem(data);
    if (response.code === 200) {
      // 上架成功
      ElMessage.success('物品上架成功');
      // 移除滚动监听
      removeInventoryScrollListener();
      listItemDialogVisible.value = false;
      
      // 重新加载我的上架物品列表
      loadMyListedItems();
      handleSearch();
      // 更新余额
      fetchUserBalance();
      
      // 重置任何可能存在的二级密码状态
      secondaryPasswordVisible.value = false;
      secondaryPasswordForm.password = '';
      pendingOperation.value = null;
    } else if (response.code === 9) {
      
      // 需要二级密码验证
      pendingOperation.value = {
        type: 'sell',
        data: data
      };
      
      secondaryPasswordVisible.value = true;
      ElMessage.warning('需要二级密码验证');
    } else {
      // 其他错误
      ElMessage.error(response.msg || '上架物品失败');
    }
  } finally {
    listItemLoading.value = false;
  }
};
</script>

<style src="./index.scss"></style>